{"version":3,"file":"index-BvzeRkqf.js","sources":["../../node_modules/react/cjs/react.production.min.js","../../node_modules/react/index.js","../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../node_modules/react/jsx-runtime.js","../../node_modules/scheduler/cjs/scheduler.production.min.js","../../node_modules/scheduler/index.js","../../node_modules/react-dom/cjs/react-dom.production.min.js","../../node_modules/react-dom/index.js","../../node_modules/react-dom/client.js","../../node_modules/@remix-run/router/dist/router.js","../../node_modules/react-router/dist/index.js","../../node_modules/react-router-dom/dist/index.js","../../node_modules/tslib/tslib.es6.mjs","../../node_modules/@supabase/functions-js/dist/module/helper.js","../../node_modules/@supabase/functions-js/dist/module/types.js","../../node_modules/@supabase/functions-js/dist/module/FunctionsClient.js","../../node_modules/@supabase/postgrest-js/dist/index.mjs","../../node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js","../../node_modules/@supabase/realtime-js/dist/module/lib/version.js","../../node_modules/@supabase/realtime-js/dist/module/lib/constants.js","../../node_modules/@supabase/realtime-js/dist/module/lib/serializer.js","../../node_modules/@supabase/realtime-js/dist/module/lib/transformers.js","../../node_modules/@supabase/phoenix/priv/static/phoenix.mjs","../../node_modules/@supabase/realtime-js/dist/module/phoenix/presenceAdapter.js","../../node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js","../../node_modules/@supabase/realtime-js/dist/module/lib/normalizeChannelError.js","../../node_modules/@supabase/realtime-js/dist/module/phoenix/channelAdapter.js","../../node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js","../../node_modules/@supabase/realtime-js/dist/module/phoenix/socketAdapter.js","../../node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js","../../node_modules/iceberg-js/dist/index.mjs","../../node_modules/@supabase/storage-js/dist/index.mjs","../../node_modules/@supabase/auth-js/dist/module/lib/version.js","../../node_modules/@supabase/auth-js/dist/module/lib/constants.js","../../node_modules/@supabase/auth-js/dist/module/lib/errors.js","../../node_modules/@supabase/auth-js/dist/module/lib/base64url.js","../../node_modules/@supabase/auth-js/dist/module/lib/helpers.js","../../node_modules/@supabase/auth-js/dist/module/lib/fetch.js","../../node_modules/@supabase/auth-js/dist/module/lib/types.js","../../node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js","../../node_modules/@supabase/auth-js/dist/module/lib/local-storage.js","../../node_modules/@supabase/auth-js/dist/module/lib/locks.js","../../node_modules/@supabase/auth-js/dist/module/lib/polyfills.js","../../node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js","../../node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js","../../node_modules/@supabase/auth-js/dist/module/lib/webauthn.js","../../node_modules/@supabase/auth-js/dist/module/GoTrueClient.js","../../node_modules/@supabase/auth-js/dist/module/AuthClient.js","../../node_modules/@supabase/supabase-js/dist/index.mjs","../../src/lib/supabase.js","../../src/lib/theme.js","../../node_modules/@capacitor/core/dist/index.js","../../src/lib/appVersion.js","../../src/lib/native.js","../../src/components/ui/Button.jsx","../../src/components/ui/Card.jsx","../../src/components/ui/Badge.jsx","../../src/components/ui/Input.jsx","../../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs","../../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs","../../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs","../../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs","../../node_modules/lucide-react/dist/esm/defaultAttributes.mjs","../../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs","../../node_modules/lucide-react/dist/esm/context.mjs","../../node_modules/lucide-react/dist/esm/Icon.mjs","../../node_modules/lucide-react/dist/esm/createLucideIcon.mjs","../../node_modules/lucide-react/dist/esm/icons/camera.mjs","../../node_modules/lucide-react/dist/esm/icons/check.mjs","../../node_modules/lucide-react/dist/esm/icons/chevron-down.mjs","../../node_modules/lucide-react/dist/esm/icons/chevron-left.mjs","../../node_modules/lucide-react/dist/esm/icons/chevron-right.mjs","../../node_modules/lucide-react/dist/esm/icons/chevron-up.mjs","../../node_modules/lucide-react/dist/esm/icons/clock.mjs","../../node_modules/lucide-react/dist/esm/icons/coffee.mjs","../../node_modules/lucide-react/dist/esm/icons/download.mjs","../../node_modules/lucide-react/dist/esm/icons/ellipsis-vertical.mjs","../../node_modules/lucide-react/dist/esm/icons/eye.mjs","../../node_modules/lucide-react/dist/esm/icons/fuel.mjs","../../node_modules/lucide-react/dist/esm/icons/grip-vertical.mjs","../../node_modules/lucide-react/dist/esm/icons/map-pin.mjs","../../node_modules/lucide-react/dist/esm/icons/menu.mjs","../../node_modules/lucide-react/dist/esm/icons/moon.mjs","../../node_modules/lucide-react/dist/esm/icons/notepad-text.mjs","../../node_modules/lucide-react/dist/esm/icons/paperclip.mjs","../../node_modules/lucide-react/dist/esm/icons/pencil.mjs","../../node_modules/lucide-react/dist/esm/icons/pin.mjs","../../node_modules/lucide-react/dist/esm/icons/pin-off.mjs","../../node_modules/lucide-react/dist/esm/icons/printer.mjs","../../node_modules/lucide-react/dist/esm/icons/route.mjs","../../node_modules/lucide-react/dist/esm/icons/share-2.mjs","../../node_modules/lucide-react/dist/esm/icons/smartphone.mjs","../../node_modules/lucide-react/dist/esm/icons/sun.mjs","../../node_modules/lucide-react/dist/esm/icons/traffic-cone.mjs","../../node_modules/lucide-react/dist/esm/icons/trash-2.mjs","../../node_modules/lucide-react/dist/esm/icons/undo-2.mjs","../../node_modules/lucide-react/dist/esm/icons/x.mjs","../../src/components/ui/Modal.jsx","../../src/lib/names.js","../../src/lib/edgeErrorMessage.js","../../src/lib/driverClock.js","../../src/components/Auth/AuthPage.jsx","../../src/components/Auth/AuthCallback.jsx","../../src/components/Auth/ResetPasswordPage.jsx","../../src/lib/pageAccess.js","../../src/lib/salesMetrics.js","../../src/lib/scrubPii.js","../../src/lib/errorReport.js","../../src/lib/chat.js","../../src/lib/sendRoute.js","../../src/lib/notifySound.js","../../src/lib/tabAlert.js","../../src/components/Messages/MessagesContext.jsx","../../src/lib/team.js","../../src/components/Layout/InviteBanner.jsx","../../src/lib/adminAudit.js","../../src/lib/peopleNames.js","../../src/lib/shiftPairing.js","../../src/lib/clockPaging.js","../../src/lib/timeclock.js","../../src/lib/scheduleDays.js","../../src/lib/scheduleEdits.js","../../src/lib/schedules.js","../../src/components/Time/ClockConfirmModal.jsx","../../src/components/Time/ClockButton.jsx","../../src/components/Layout/SettingsMenu.jsx","../../src/components/Layout/ReportsMenu.jsx","../../src/components/Layout/ManageMenu.jsx","../../src/lib/serviceDue.js","../../src/lib/oilChange.js","../../src/lib/oilDue.js","../../src/lib/vehicles.js","../../src/lib/insuranceDue.js","../../src/components/Layout/MaintenanceAlert.jsx","../../src/lib/dispatcherChat.js","../../src/lib/dmDirectory.js","../../src/lib/dispatcherDm.js","../../src/lib/refreshOnReturn.js","../../src/components/Dispatch/DispatcherChatCard.jsx","../../src/components/Dispatch/DispatcherChatButton.jsx","../../src/components/Layout/DeliveryTimeButton.jsx","../../node_modules/canvas-confetti/dist/confetti.module.mjs","../../src/components/Birthday/BirthdayCelebration.jsx","../../src/components/Layout/AppShell.jsx","../../node_modules/@dnd-kit/utilities/dist/utilities.esm.js","../../node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js","../../node_modules/@dnd-kit/core/dist/core.esm.js","../../node_modules/@dnd-kit/sortable/dist/sortable.esm.js","../../src/lib/imageFit.js","../../src/lib/stopInvoices.js","../../src/lib/routeOrderLog.js","../../node_modules/@googlemaps/js-api-loader/dist/index.js","../../src/lib/googleMaps.js","../../src/lib/formatAddress.js","../../src/lib/addressPrecision.js","../../src/lib/geocode.js","../../src/lib/plannedPath.js","../../src/lib/planBudget.js","../../src/lib/routing.js","../../src/lib/placeCandidates.js","../../src/lib/addAddresses.js","../../src/lib/outreach.js","../../src/lib/navTarget.js","../../src/lib/mapsUrl.js","../../src/lib/driverFocus.js","../../src/lib/recallSplit.js","../../src/lib/thresholds.js","../../src/lib/tripSnapshot.js","../../src/lib/runs.js","../../src/lib/runNudge.js","../../src/lib/orgDay.js","../../src/lib/vehicleAssignments.js","../../src/lib/gps.js","../../src/lib/phonePings.js","../../src/components/Dispatch/AfterHoursAlertBanner.jsx","../../src/lib/boardRows.js","../../src/lib/board.js","../../src/lib/codDefault.js","../../src/lib/notReady.js","../../src/lib/doordash.js","../../src/lib/doordashNudge.js","../../src/lib/doordashNudgeLog.js","../../src/lib/stopText.js","../../src/lib/timeWindows.js","../../src/lib/locationPhone.js","../../src/lib/addressBlocks.js","../../src/components/Dispatch/AddressAutocomplete.jsx","../../supabase/functions/_shared/orderimport.js","../../src/lib/orderImport.js","../../src/lib/scanAddress.js","../../supabase/functions/_shared/accountvisits.js","../../src/lib/accountVisits.js","../../supabase/functions/_shared/marketingpieces.js","../../src/lib/marketingPieces.js","../../src/components/Dispatch/AddressAccumulator.jsx","../../src/lib/savedAddresses.js","../../src/components/Dispatch/SavedAddressesManager.jsx","../../src/components/Dispatch/SavedAddressesCard.jsx","../../src/components/Dispatch/AccountVisits.jsx","../../src/components/Dispatch/PieceSelect.jsx","../../src/components/Dispatch/DueVisitsPanel.jsx","../../src/components/Dispatch/piecesContext.js","../../src/components/Dispatch/StopChip.jsx","../../src/components/Dispatch/UnassignedPanel.jsx","../../src/lib/format.js","../../src/components/Dispatch/StopTextPanel.jsx","../../src/lib/legDeltas.js","../../src/lib/legAttribution.js","../../src/lib/forgiveness.js","../../src/components/Messages/ChatThread.jsx","../../src/components/Dispatch/LiveRouteModal.jsx","../../src/components/Vehicles/VehicleIcon.jsx","../../src/lib/freeRoam.js","../../src/lib/places.js","../../src/components/Dispatch/PickupSuggestPanel.jsx","../../src/lib/outreachData.js","../../src/components/Dispatch/useWinBackNear.js","../../src/components/Dispatch/WinBackSuggestPanel.jsx","../../src/lib/fuel.js","../../src/components/Fuel/FuelEvidence.jsx","../../src/lib/pod.js","../../src/components/Pod/PodProofPanel.jsx","../../src/components/Dispatch/DriverBoard.jsx","../../src/components/Dispatch/DoorDashPanel.jsx","../../src/components/Dispatch/BusinessPickerModal.jsx","../../src/components/Dispatch/PhotoScanButton.jsx","../../src/lib/invoiceMatch.js","../../src/components/Dispatch/InvoiceFinder.jsx","../../src/components/Dispatch/StopDuplicateModal.jsx","../../src/lib/vehicleChecks.js","../../src/components/Dispatch/VehicleAlertModal.jsx","../../src/components/Dispatch/DispatchScreen.jsx","../../src/components/Drivers/ScheduleModal.jsx","../../src/components/Drivers/PairPhoneModal.jsx","../../src/lib/captureRules.js","../../src/components/Drivers/DriversScreen.jsx","../../src/components/Tooltip.jsx","../../src/components/History/TripMapModal.jsx","../../src/components/History/DriverReportModal.jsx","../../src/components/History/HistoryScreen.jsx","../../src/lib/driverPay.js","../../src/components/Reports/ReportsScreen.jsx","../../src/components/Reports/DeliveryTimeScreen.jsx","../../src/components/Reports/DeliveryHistoryScreen.jsx","../../src/lib/driverAttribution.js","../../src/components/Reports/DriverDataScreen.jsx","../../src/lib/doordashReport.js","../../src/components/Reports/DoorDashScreen.jsx","../../src/lib/employees.js","../../src/components/Settings/SettingsScreen.jsx","../../src/components/Settings/ActivityScreen.jsx","../../src/components/Auth/ChangePinGate.jsx","../../src/components/Rules/RulesScreen.jsx","../../src/components/Messages/MessagesScreen.jsx","../../src/components/Map/MapScreen.jsx","../../src/lib/registration.js","../../src/lib/vin.js","../../src/components/Vehicles/VehiclesScreen.jsx","../../src/lib/features.js","../../src/components/Customers/CustomersScreen.jsx","../../src/components/Customers/PinSuggestions.jsx","../../src/components/Customers/PinAdjustmentsScreen.jsx","../../src/components/Recurring/RecurringScreen.jsx","../../src/components/Schedule/ScheduleReport.jsx","../../src/lib/schedulePrint.js","../../src/components/Schedule/PrintSchedule.jsx","../../src/components/Schedule/TeamSchedule.jsx","../../src/components/Schedule/SchedulesScreen.jsx","../../src/components/Time/PunchEditor.jsx","../../src/lib/payroll.js","../../src/lib/csv.js","../../src/components/Time/HoursExport.jsx","../../src/lib/ptoMath.js","../../src/lib/pto.js","../../src/components/Driver/DriverPortal.jsx","../../src/components/Time/TimeScreen.jsx","../../src/lib/clockIpSettings.js","../../src/components/common/screenshots.js","../../src/components/common/ScreenshotGallery.jsx","../../src/components/SiteSetup/OrderInboxCard.jsx","../../src/lib/orgMedia.js","../../src/lib/webhookLog.js","../../src/components/SiteSetup/WebhookDeliveryLog.jsx","../../src/components/SiteSetup/MarketingPiecesEditor.jsx","../../src/components/SiteSetup/SiteSetupScreen.jsx","../../src/components/Payroll/PayrollScreen.jsx","../../src/lib/fuelCsv.js","../../src/components/Fuel/AddReceiptModal.jsx","../../src/components/Fuel/FuelScreen.jsx","../../src/components/Rev/CompetitorTable.jsx","../../src/components/Rev/RevPage.jsx","../../src/lib/companies.js","../../src/components/Companies/CompaniesScreen.jsx","../../src/lib/updateGate.js","../../src/components/DeployWatcher.jsx","../../src/components/DevNotice.jsx","../../src/components/ErrorBoundary.jsx","../../src/components/Marketing/competitorSlugs.js","../../src/App.jsx","../../src/main.jsx"],"sourcesContent":["/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\"\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n return {\n usr: location.state,\n key: location.key,\n idx: index\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n let index = getIndex();\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\n }\n }\n function createURL(to) {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (manifest === void 0) {\n manifest = {};\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, mapRouteProperties(route), {\n id\n });\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n id,\n children: undefined\n });\n manifest[id] = pathOrLayoutRoute;\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n }\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\nfunction matchRoutesImpl(routes, locationArg, basename, allowPartial) {\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(branches[i], decoded, allowPartial);\n }\n return matches;\n}\nfunction convertRouteMatchToUiMatch(match, loaderData) {\n let {\n route,\n pathname,\n params\n } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle\n };\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n let flattenRoute = (route, index, relativePath) => {\n let meta = {\n relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n routes.forEach((route, index) => {\n var _route$path;\n // coarse-grain check for optional params\n if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments;\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = [];\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n // for absolute paths, ensure `/` instead of empty segment\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname, allowPartial) {\n if (allowPartial === void 0) {\n allowPartial = false;\n }\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n let route = meta.route;\n if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {\n match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false\n }, remainingPathname);\n }\n if (!match) {\n return null;\n }\n Object.assign(matchedParams, match.params);\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n let path = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n path = path.replace(/\\*$/, \"/*\");\n }\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n // Apply the splat\n return stringify(params[star]);\n }\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n return stringify(param);\n }\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter(segment => !!segment);\n return prefix + segments.join(\"/\");\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = compiledParams.reduce((memo, _ref, index) => {\n let {\n paramName,\n isOptional\n } = _ref;\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n let params = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:([\\w-]+)(\\?)?/g, (_, paramName, isOptional) => {\n params.push({\n paramName,\n isOptional: isOptional != null\n });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n params.push({\n paramName: \"*\"\n });\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, params];\n}\nfunction decodePath(value) {\n try {\n return value.split(\"/\").map(v => decodeURIComponent(v).replace(/\\//g, \"%2F\")).join(\"/\");\n } catch (error) {\n warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\nconst ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst isAbsoluteUrl = url => ABSOLUTE_URL_REGEX$1.test(url);\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname;\n if (toPathname) {\n if (isAbsoluteUrl(toPathname)) {\n pathname = toPathname;\n } else {\n if (toPathname.includes(\"//\")) {\n let oldPathname = toPathname;\n toPathname = removeDoubleSlashes(toPathname);\n warning(false, \"Pathnames cannot have embedded double slashes - normalizing \" + (oldPathname + \" -> \" + toPathname));\n }\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n }\n } else {\n pathname = fromPathname;\n }\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"]. Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nfunction getResolveToMatches(matches, v7_relativeSplatPath) {\n let pathMatches = getPathContributingMatches(matches);\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);\n }\n return pathMatches.map(match => match.pathnameBase);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from;\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n }\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from);\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\nconst removeDoubleSlashes = path => path.replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst joinPaths = paths => removeDoubleSlashes(paths.join(\"/\"));\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass DataWithResponseInit {\n constructor(data, init) {\n this.type = \"DataWithResponseInit\";\n this.data = data;\n this.init = init || null;\n }\n}\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nfunction data(data, init) {\n return new DataWithResponseInit(data, typeof init === \"number\" ? {\n status: init\n } : init);\n}\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data, responseInit) {\n this.pendingKeysSet = new Set();\n this.subscribers = new Set();\n this.deferredKeys = [];\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n this.init = responseInit;\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeysSet.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n Object.defineProperty(promise, \"_error\", {\n get: () => undefinedError\n });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref3) => {\n let [key, value] = _ref3;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirectDocument = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst replace = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nclass ErrorResponseImpl {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\n\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_BLOCKER = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let mapRouteProperties;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Routes keyed by ID\n let manifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n let inFlightDataRoutes;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n // Config driven behavior flags\n let future = _extends({\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false\n }, init.future);\n // Cleanup function for history\n let unlistenHistory = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors = null;\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname\n });\n let {\n matches,\n route\n } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n let initialized;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some(m => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some(m => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);\n initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map(),\n blockers: new Map()\n };\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction = Action.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController;\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions = new Map();\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener = null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads = new Set();\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate = undefined;\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location,\n delta\n } = _ref;\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n warning(blockerFunctions.size === 0 || delta != null, \"You are trying to use a blocker on a POP navigation to a location \" + \"that was not created by @remix-run/router. This will fail silently in \" + \"production. This can happen if you are navigating outside the router \" + \"via `window.history.pushState`/`window.location.hash` instead of using \" + \"router navigation APIs. This can also happen if you are using \" + \"createHashRouter and the user manually changes the URL.\");\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction\n });\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise(resolve => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return startNavigation(historyAction, location);\n });\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () => routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location, {\n initialHydration: true\n });\n }\n return router;\n }\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n // Subscribe to state updates for the router\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n // Update our state and notify the calling context of the change\n function updateState(newState, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state = _extends({}, state, newState);\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers = [];\n let deletedFetchersKeys = [];\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach(key => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach(subscriber => subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true\n }));\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach(key => state.fetchers.delete(key));\n deletedFetchersKeys.forEach(key => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));\n }\n }\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(location, newState, _temp) {\n var _location$state, _location$state2;\n let {\n flushSync\n } = _temp === void 0 ? {} : _temp;\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n let actionData;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n }\n let viewTransitionOpts;\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === Action.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n }\n updateState(_extends({}, newState, {\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset,\n blockers\n }), {\n viewTransitionOpts,\n flushSync: flushSync === true\n });\n // Reset stateful navigation vars\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n if (userReplace === true) {\n historyAction = Action.Replace;\n } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = Action.Replace;\n }\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let flushSync = (opts && opts.flushSync) === true;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync\n });\n }\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n });\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n }\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true\n });\n }\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?\n // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a
\n // which will default to a navigation to /page\n if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n completeNavigation(location, {\n matches\n }, {\n flushSync\n });\n return;\n }\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n }, {\n flushSync\n });\n return;\n }\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);\n let pendingActionResult;\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [findNearestBoundary(matches).route.id, {\n type: ResultType.error,\n error: opts.pendingError\n }];\n } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n // Call action if we received an action submission\n let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {\n replace: opts.replace,\n flushSync\n });\n if (actionResult.shortCircuited) {\n return;\n }\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {\n pendingNavigationController = null;\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error\n }\n });\n return;\n }\n }\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n // Create a GET request for the loaders\n request = createClientSideRequest(init.history, request.url, request.signal);\n }\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors\n } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);\n if (shortCircuited) {\n return;\n }\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n completeNavigation(location, _extends({\n matches: updatedMatches || matches\n }, getActionDataForCommit(pendingActionResult), {\n loaderData,\n errors\n }));\n }\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(request, location, submission, matches, isFogOfWar, opts) {\n if (opts === void 0) {\n opts = {};\n }\n interruptActiveLoads();\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({\n navigation\n }, {\n flushSync: opts.flushSync === true\n });\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [boundaryId, {\n type: ResultType.error,\n error: discoverResult.error\n }]\n };\n } else if (!discoverResult.matches) {\n let {\n notFoundMatches,\n error,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n pendingActionResult: [route.id, {\n type: ResultType.error,\n error\n }]\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n // Call our action and get the result\n let result;\n let actionMatch = getTargetMatch(matches, location);\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id\n })\n };\n } else {\n let results = await callDataStrategy(\"action\", state, request, [actionMatch], matches, null);\n result = results[actionMatch.route.id];\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n }\n if (isRedirectResult(result)) {\n let replace;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(result.response.headers.get(\"Location\"), new URL(request.url), basename, init.history);\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace\n });\n return {\n shortCircuited: true\n };\n }\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = Action.Push;\n }\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result]\n };\n }\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result]\n };\n }\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(_extends({\n navigation: loadingNavigation\n }, actionData !== undefined ? {\n actionData\n } : {}), {\n flushSync\n });\n }\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error\n }\n };\n } else if (!discoverResult.matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));\n pendingNavigationLoadId = ++incrementingLoadId;\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, _extends({\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null\n }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {}), {\n flushSync\n });\n return {\n shortCircuited: true\n };\n }\n if (shouldUpdateNavigationState) {\n let updates = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, {\n flushSync\n });\n }\n revalidatingFetchers.forEach(rf => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace\n });\n return {\n shortCircuited: true\n };\n }\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace\n });\n return {\n shortCircuited: true\n };\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe(aborted => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = _extends({}, state.errors, errors);\n }\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n return _extends({\n matches,\n loaderData,\n errors\n }, shouldUpdateFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {});\n }\n function getUpdatedActionData(pendingActionResult) {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n function getUpdatedRevalidatingFetchers(revalidatingFetchers) {\n revalidatingFetchers.forEach(rf => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(key, routeId, href, opts) {\n if (isServer) {\n throw new Error(\"router.fetch() was called during the server render, but it shouldn't be. \" + \"You are likely calling a useFetcher() method in the body of your component. \" + \"Try moving it to a useEffect or a callback.\");\n }\n abortFetcher(key);\n let flushSync = (opts && opts.flushSync) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n if (!matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: normalizedPath\n }), {\n flushSync\n });\n return;\n }\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);\n if (error) {\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return;\n }\n let match = getTargetMatch(matches, path);\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);\n return;\n }\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, {\n routeId,\n path\n });\n handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);\n }\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n function detectAndHandle405Error(m) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId\n });\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return true;\n }\n return false;\n }\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\"action\", state, fetchRequest, [match], requestMatches, key);\n let actionResult = actionResults[match.route.id];\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset\n });\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches = state.navigation.state !== \"idle\" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;\n invariant(matches, \"Didn't find any matches after fetcher action\");\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));\n abortController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n if (abortController.signal.aborted) {\n return;\n }\n abortController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(revalidationRequest, redirect.result, false, {\n preventScrollReset\n });\n }\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(revalidationRequest, redirect.result, false, {\n preventScrollReset\n });\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n abortStaleFetchLoads(loadId);\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers)\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),\n fetchers: new Map(state.fetchers)\n });\n isRevalidationRequired = false;\n }\n }\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\"loader\", state, fetchRequest, [match], matches, key);\n let result = results[match.route.id];\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n }\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n if (fetchRequest.signal.aborted) {\n return;\n }\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset\n });\n return;\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {\n let {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace\n } = _temp2 === void 0 ? {} : _temp2;\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true\n });\n if (isBrowser) {\n let isDocumentReload = false;\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n let redirectHistoryAction = replace === true || redirect.response.headers.has(\"X-Remix-Replace\") ? Action.Replace : Action.Push;\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let {\n formMethod,\n formAction,\n formEncType\n } = state.navigation;\n if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: _extends({}, activeSubmission, {\n formAction: location\n }),\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(redirectLocation, submission);\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined\n });\n }\n }\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {\n let results;\n let dataResults = {};\n try {\n results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach(m => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e\n };\n });\n return dataResults;\n }\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(result);\n }\n }\n return dataResults;\n }\n async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {\n let currentMatches = state.matches;\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\"loader\", state, request, matchesToLoad, matches, null);\n let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\"loader\", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return {\n [f.key]: result\n };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path\n })\n }\n });\n }\n }));\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});\n await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);\n return {\n loaderResults,\n fetcherResults\n };\n }\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n function updateFetcherState(key, fetcher, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state.fetchers.set(key, fetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function setFetcherError(key, routeId, error, opts) {\n if (opts === void 0) {\n opts = {};\n }\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error\n },\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function getFetcher(key) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n function deleteFetcher(key) {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (fetchControllers.has(key) && !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n function deleteFetcherAndUpdateState(key) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n updateState({\n fetchers: new Map(state.fetchers)\n });\n }\n function abortFetcher(key) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n function markFetchersDone(keys) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n function markFetchRedirectsDone() {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n function abortStaleFetchLoads(landedId) {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n function getBlocker(key, fn) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n return blocker;\n }\n function deleteBlocker(key) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key, newBlocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(blocker.state === \"unblocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"proceeding\" || blocker.state === \"blocked\" && newBlocker.state === \"unblocked\" || blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\", \"Invalid blocker state transition: \" + blocker.state + \" -> \" + newBlocker.state);\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({\n blockers\n });\n }\n function shouldBlockNavigation(_ref2) {\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = _ref2;\n if (blockerFunctions.size === 0) {\n return;\n }\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({\n currentLocation,\n nextLocation,\n historyAction\n })) {\n return blockerKey;\n }\n }\n function handleNavigational404(pathname) {\n let error = getInternalRouterError(404, {\n pathname\n });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let {\n matches,\n route\n } = getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n return {\n notFoundMatches: matches,\n route,\n error\n };\n }\n function cancelActiveDeferreds(predicate) {\n let cancelledRouteIds = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(positions, getPosition, getKey) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({\n restoreScrollPosition: y\n });\n }\n }\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n function getScrollKey(location, matches) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));\n return key || location.key;\n }\n return location.key;\n }\n function saveScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n function getSavedScrollPosition(location, matches) {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n function checkFogOfWar(matches, routesToUse, pathname) {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: fogMatches || []\n };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: partialMatches\n };\n }\n }\n }\n return {\n active: false,\n matches: null\n };\n }\n async function discoverRoutes(matches, pathname, signal, fetcherKey) {\n if (!patchRoutesOnNavigationImpl) {\n return {\n type: \"success\",\n matches\n };\n }\n let partialMatches = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);\n }\n });\n } catch (e) {\n return {\n type: \"error\",\n error: e,\n partialMatches\n };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n if (signal.aborted) {\n return {\n type: \"aborted\"\n };\n }\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return {\n type: \"success\",\n matches: newMatches\n };\n }\n let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n // Avoid loops if the second pass results in the same partial matches\n if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {\n return {\n type: \"success\",\n matches: null\n };\n }\n partialMatches = newPartialMatches;\n }\n }\n function _internalSetRoutes(newRoutes) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);\n }\n function patchRoutes(routeId, children) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: to => init.history.createHref(to),\n encodeLocation: to => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes\n };\n return router;\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\nconst UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\nfunction createStaticHandler(routes, opts) {\n invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n let manifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties;\n if (opts != null && opts.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts != null && opts.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future = _extends({\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false\n }, opts ? opts.future : null);\n let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(request, _temp3) {\n let {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy\n } = _temp3 === void 0 ? {} : _temp3;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, {\n method\n });\n let {\n matches: methodNotAllowedMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);\n if (isResponse(result)) {\n return result;\n }\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return _extends({\n location,\n basename\n }, result);\n }\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(request, _temp4) {\n let {\n routeId,\n requestContext,\n dataStrategy\n } = _temp4 === void 0 ? {} : _temp4;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, {\n method\n });\n } else if (!matches) {\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);\n if (isResponse(result)) {\n return result;\n }\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n if (result.loaderData) {\n var _result$activeDeferre;\n let data = Object.values(result.loaderData)[0];\n if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n return undefined;\n }\n async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {\n invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);\n return result;\n }\n let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);\n return isResponse(result) ? result : _extends({}, result, {\n actionData: null,\n actionHeaders: {}\n });\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {\n let result;\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n } else {\n let results = await callDataStrategy(\"action\", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);\n result = results[actionMatch.route.id];\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")\n }\n });\n }\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, {\n type: \"defer-action\"\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n }\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: {\n [actionMatch.route.id]: result.data\n },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal\n });\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);\n // action status codes take precedence over loader status codes\n return _extends({}, context, {\n statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,\n actionData: null,\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);\n return _extends({}, context, {\n actionData: {\n [actionMatch.route.id]: result.data\n }\n }, result.statusCode ? {\n statusCode: result.statusCode\n } : {}, {\n actionHeaders: result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {}\n });\n }\n async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {\n let isRouteRequest = routeMatch != null;\n // Short circuit if we have no loaders to run (queryRoute())\n if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch == null ? void 0 : routeMatch.route.id\n });\n }\n let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;\n let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce((acc, m) => Object.assign(acc, {\n [m.route.id]: null\n }), {}),\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null\n };\n }\n let results = await callDataStrategy(\"loader\", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));\n matches.forEach(match => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n return _extends({}, context, {\n matches,\n activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null\n });\n }\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {\n let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);\n let dataResults = {};\n await Promise.all(matches.map(async match => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);\n }));\n return dataResults;\n }\n return {\n dataRoutes,\n query,\n queryRoute\n };\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nfunction getStaticContextFromError(routes, context, error) {\n let newContext = _extends({}, context, {\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error\n }\n });\n return newContext;\n}\nfunction throwStaticHandlerAbortedError(request, isRouteRequest, future) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted: \" + request.method + \" \" + request.url);\n}\nfunction isSubmissionNavigation(opts) {\n return opts != null && (\"formData\" in opts && opts.formData != null || \"body\" in opts && opts.body !== undefined);\n}\nfunction normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {\n let contextualMatches;\n let activeRouteMatch;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n // Resolve the relative path\n let path = resolveTo(to ? to : \".\", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === \"path\");\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search ? path.search.replace(/^\\?/, \"?index&\") : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter(v => v).forEach(v => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? \"?\" + qs : \"\";\n }\n }\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n return createPath(path);\n}\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return {\n path\n };\n }\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, {\n method: opts.formMethod\n })\n };\n }\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, {\n type: \"invalid-body\"\n })\n });\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();\n let formAction = stripHashFromPath(path);\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n let text = typeof opts.body === \"string\" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce((acc, _ref3) => {\n let [name, value] = _ref3;\n return \"\" + acc + name + \"=\" + value + \"\\n\";\n }, \"\") : String(opts.body);\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text\n }\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n try {\n let json = typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined\n }\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n invariant(typeof FormData === \"function\", \"FormData is not available in this environment\");\n let searchParams;\n let formData;\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n let submission = {\n formMethod,\n formAction,\n formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined\n };\n if (isMutationMethod(submission.formMethod)) {\n return {\n path,\n submission\n };\n }\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = \"?\" + searchParams;\n return {\n path: createPath(parsedPath),\n submission\n };\n}\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {\n if (includeBoundary === void 0) {\n includeBoundary = false;\n }\n let index = matches.findIndex(m => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\nfunction getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {\n let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);\n }\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;\n let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let {\n route\n } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (route.loader == null) {\n return false;\n }\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n // Always call the loader on new route instances and pending defer cancellations\n if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {\n return true;\n }\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n return shouldRevalidateLoader(match, _extends({\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false :\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)\n }));\n });\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {\n return;\n }\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null\n });\n return;\n }\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (fetcher && fetcher.state !== \"idle\" && fetcher.data === undefined) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired\n }));\n }\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController()\n });\n }\n });\n return [navigationMatches, revalidatingFetchers];\n}\nfunction shouldLoadRouteOnHydration(route, loaderData, errors) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n currentPath != null && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n );\n}\nfunction shouldRevalidateLoader(loaderMatch, arg) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n return arg.defaultShouldRevalidate;\n}\nfunction patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {\n var _childrenToPatch;\n let childrenToPatch;\n if (routeId) {\n let route = manifest[routeId];\n invariant(route, \"No route found to patch children into: routeId = \" + routeId);\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));\n let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || \"_\", \"patch\", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || \"0\")], manifest);\n childrenToPatch.push(...newRoutes);\n}\nfunction isSameRoute(newRoute, existingRoute) {\n // Most optimal check is by id\n if (\"id\" in newRoute && \"id\" in existingRoute && newRoute.id === existingRoute.id) {\n return true;\n }\n // Second is by pathing differences\n if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {\n return false;\n }\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {\n return true;\n }\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children.every((aChild, i) => {\n var _existingRoute$childr;\n return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));\n });\n}\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(route, mapRouteProperties, manifest) {\n if (!route.lazy) {\n return;\n }\n let lazyRoute = await route.lazy();\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue = routeToUpdate[lazyRouteProperty];\n let isPropertyStaticallyDefined = staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n warning(!isPropertyStaticallyDefined, \"Route \\\"\" + routeToUpdate.id + \"\\\" has a static property \\\"\" + lazyRouteProperty + \"\\\" \" + \"defined but its lazy function is also returning a value for this property. \" + (\"The lazy route property \\\"\" + lazyRouteProperty + \"\\\" will be ignored.\"));\n if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {\n routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];\n }\n }\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {\n lazy: undefined\n }));\n}\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy(_ref4) {\n let {\n matches\n } = _ref4;\n let matchesToLoad = matches.filter(m => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map(m => m.resolve()));\n return results.reduce((acc, result, i) => Object.assign(acc, {\n [matchesToLoad[i].route.id]: result\n }), {});\n}\nasync function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {\n let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve = async handlerOverride => {\n if (handlerOverride && request.method === \"GET\" && (match.route.lazy || match.route.loader)) {\n shouldLoad = true;\n }\n return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({\n type: ResultType.data,\n result: undefined\n });\n };\n return _extends({}, match, {\n shouldLoad,\n resolve\n });\n });\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext\n });\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n return results;\n}\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {\n let result;\n let onReject;\n let runHandler = handler => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => reject = r);\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n let actualHandler = ctx => {\n if (typeof handler !== \"function\") {\n return Promise.reject(new Error(\"You cannot call the handler for a route which defines a boolean \" + (\"\\\"\" + type + \"\\\" [routeId: \" + match.route.id + \"]\")));\n }\n return handler({\n request,\n params: match.params,\n context: staticContext\n }, ...(ctx !== undefined ? [ctx] : []));\n };\n let handlerPromise = (async () => {\n try {\n let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());\n return {\n type: \"data\",\n result: val\n };\n } catch (e) {\n return {\n type: \"error\",\n result: e\n };\n }\n })();\n return Promise.race([handlerPromise, abortPromise]);\n };\n try {\n let handler = match.route[type];\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch(e => {\n handlerError = e;\n }), loadRoutePromise]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return {\n type: ResultType.data,\n result: undefined\n };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname\n });\n } else {\n result = await runHandler(handler);\n }\n invariant(result.result !== undefined, \"You defined \" + (type === \"action\" ? \"an action\" : \"a loader\") + \" for route \" + (\"\\\"\" + match.route.id + \"\\\" but didn't return anything from your `\" + type + \"` \") + \"function. Please return a value or `null`.\");\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return {\n type: ResultType.error,\n result: e\n };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n return result;\n}\nasync function convertDataStrategyResultToDataResult(dataStrategyResult) {\n let {\n result,\n type\n } = dataStrategyResult;\n if (isResponse(result)) {\n let data;\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return {\n type: ResultType.error,\n error: e\n };\n }\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers\n };\n }\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers\n };\n }\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n var _result$init3, _result$init4;\n if (result.data instanceof Error) {\n var _result$init, _result$init2;\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,\n headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined\n };\n }\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined\n };\n }\n if (isDeferredData(result)) {\n var _result$init5, _result$init6;\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,\n headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)\n };\n }\n if (isDataWithResponseInit(result)) {\n var _result$init7, _result$init8;\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,\n headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined\n };\n }\n return {\n type: ResultType.data,\n data: result\n };\n}\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {\n let location = response.headers.get(\"Location\");\n invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);\n location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);\n response.headers.set(\"Location\", location);\n }\n return response;\n}\nfunction normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\"about:\", \"blob:\", \"chrome:\", \"chrome-untrusted:\", \"content:\", \"data:\", \"devtools:\", \"file:\", \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\"];\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n return location;\n}\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(history, location, signal, submission) {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init = {\n signal\n };\n if (submission && isMutationMethod(submission.formMethod)) {\n let {\n formMethod,\n formEncType\n } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n if (formEncType === \"application/json\") {\n init.headers = new Headers({\n \"Content-Type\": formEncType\n });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (formEncType === \"application/x-www-form-urlencoded\" && submission.formData) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n let searchParams = new URLSearchParams();\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n return searchParams;\n}\nfunction convertSearchParamsToFormData(searchParams) {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\nfunction processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {\n // Fill in loaderData/errors from our loaders\n let loaderData = {};\n let errors = null;\n let statusCode;\n let foundError = false;\n let loaderHeaders = {};\n let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;\n // Process loader results into state.loaderData/state.errors\n matches.forEach(match => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n errors = errors || {};\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = {\n [pendingActionResult[0]]: pendingError\n };\n loaderData[pendingActionResult[0]] = undefined;\n }\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders\n };\n}\nfunction processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {\n let {\n loaderData,\n errors\n } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble\n );\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach(rf => {\n let {\n key,\n match,\n controller\n } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = _extends({}, errors, {\n [boundaryMatch.route.id]: result.error\n });\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n return {\n loaderData,\n errors\n };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n let mergedLoaderData = _extends({}, newLoaderData);\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\nfunction getActionDataForCommit(pendingActionResult) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1]) ? {\n // Clear out prior actionData on errors\n actionData: {}\n } : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data\n }\n };\n}\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(matches, routeId) {\n let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];\n return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];\n}\nfunction getShortCircuitMatches(routes) {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === \"/\") || {\n id: \"__shim-error-route__\"\n };\n return {\n matches: [{\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route\n }],\n route\n };\n}\nfunction getInternalRouterError(status, _temp5) {\n let {\n pathname,\n routeId,\n method,\n type,\n message\n } = _temp5 === void 0 ? {} : _temp5;\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide a `loader` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = \"Route \\\"\" + routeId + \"\\\" does not match URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = \"No route matches URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method.toUpperCase() + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide an `action` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (method) {\n errorMessage = \"Invalid request method \\\"\" + method.toUpperCase() + \"\\\"\";\n }\n }\n return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);\n}\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results) {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return {\n key,\n result\n };\n }\n }\n}\nfunction stripHashFromPath(path) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath(_extends({}, parsedPath, {\n hash: \"\"\n }));\n}\nfunction isHashChangeOnly(a, b) {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\nfunction isDataStrategyResult(result) {\n return result != null && typeof result === \"object\" && \"type\" in result && \"result\" in result && (result.type === ResultType.data || result.type === ResultType.error);\n}\nfunction isRedirectDataStrategyResultResult(result) {\n return isResponse(result.result) && redirectStatusCodes.has(result.result.status);\n}\nfunction isDeferredResult(result) {\n return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n return (result && result.type) === ResultType.redirect;\n}\nfunction isDataWithResponseInit(value) {\n return typeof value === \"object\" && value != null && \"type\" in value && \"data\" in value && \"init\" in value && value.type === \"DataWithResponseInit\";\n}\nfunction isDeferredData(value) {\n let deferred = value;\n return deferred && typeof deferred === \"object\" && typeof deferred.data === \"object\" && typeof deferred.subscribe === \"function\" && typeof deferred.cancel === \"function\" && typeof deferred.resolveData === \"function\";\n}\nfunction isResponse(value) {\n return value != null && typeof value.status === \"number\" && typeof value.statusText === \"string\" && typeof value.headers === \"object\" && typeof value.body !== \"undefined\";\n}\nfunction isRedirectResponse(result) {\n if (!isResponse(result)) {\n return false;\n }\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\nfunction isValidMethod(method) {\n return validRequestMethods.has(method.toLowerCase());\n}\nfunction isMutationMethod(method) {\n return validMutationMethods.has(method.toLowerCase());\n}\nasync function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n let currentMatch = currentMatches.find(m => m.route.id === match.route.id);\n let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then(result => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\nasync function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let {\n key,\n routeId,\n controller\n } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(controller, \"Expected an AbortController for revalidating fetcher deferred result\");\n await resolveDeferredData(result, controller.signal, true).then(result => {\n if (result) {\n results[key] = result;\n }\n });\n }\n }\n}\nasync function resolveDeferredData(result, signal, unwrap) {\n if (unwrap === void 0) {\n unwrap = false;\n }\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e\n };\n }\n }\n return {\n type: ResultType.data,\n data: result.deferredData.data\n };\n}\nfunction hasNakedIndexQuery(search) {\n return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n}\nfunction getTargetMatch(matches, location) {\n let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || \"\")) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\nfunction getSubmissionFromNavigation(navigation) {\n let {\n formMethod,\n formAction,\n formEncType,\n text,\n formData,\n json\n } = navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined\n };\n }\n}\nfunction getLoadingNavigation(location, submission) {\n if (submission) {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n } else {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n };\n return navigation;\n }\n}\nfunction getSubmittingNavigation(location, submission) {\n let navigation = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n}\nfunction getLoadingFetcher(submission, data) {\n if (submission) {\n let fetcher = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data\n };\n return fetcher;\n } else {\n let fetcher = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n }\n}\nfunction getSubmittingFetcher(submission, existingFetcher) {\n let fetcher = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined\n };\n return fetcher;\n}\nfunction getDoneFetcher(data) {\n let fetcher = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n}\nfunction restoreAppliedTransitions(_window, transitions) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\nfunction persistAppliedTransitions(_window, transitions) {\n if (transitions.size > 0) {\n let json = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));\n } catch (error) {\n warning(false, \"Failed to save applied view transitions in sessionStorage (\" + error + \").\");\n }\n }\n}\n//#endregion\n\nexport { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, decodePath as UNSAFE_decodePath, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, data, defer, generatePath, getStaticContextFromError, getToPathname, isDataWithResponseInit, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, replace, resolvePath, resolveTo, stripBasename };\n//# sourceMappingURL=router.js.map\n","/**\n * React Router v6.30.4\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nimport * as React from 'react';\nimport { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';\nexport { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, replace, resolvePath } from '@remix-run/router';\n\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\n\nconst DataRouterContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterContext.displayName = \"DataRouter\";\n}\nconst DataRouterStateContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\nconst AwaitContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n AwaitContext.displayName = \"Await\";\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\n\nconst NavigationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n NavigationContext.displayName = \"Navigation\";\n}\nconst LocationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n LocationContext.displayName = \"Location\";\n}\nconst RouteContext = /*#__PURE__*/React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false\n});\nif (process.env.NODE_ENV !== \"production\") {\n RouteContext.displayName = \"Route\";\n}\nconst RouteErrorContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n RouteErrorContext.displayName = \"RouteError\";\n}\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nfunction useHref(to, _temp) {\n let {\n relative\n } = _temp === void 0 ? {} : _temp;\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useHref() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n basename,\n navigator\n } = React.useContext(NavigationContext);\n let {\n hash,\n pathname,\n search\n } = useResolvedPath(to, {\n relative\n });\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname = pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n return navigator.createHref({\n pathname: joinedPathname,\n search,\n hash\n });\n}\n\n/**\n * Returns true if this component is a descendant of a ``.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nfunction useInRouterContext() {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nfunction useLocation() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useLocation() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nfunction useNavigationType() {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * ``.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nfunction useMatch(pattern) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useMatch() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n pathname\n } = useLocation();\n return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\n\nconst navigateEffectWarning = \"You should call navigate() in a React.useEffect(), not when \" + \"your component is first rendered.\";\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(cb) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by ``s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nfunction useNavigate() {\n let {\n isDataRoute\n } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\nfunction useNavigateUnstable() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useNavigate() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let dataRouterContext = React.useContext(DataRouterContext);\n let {\n basename,\n future,\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === \"path\");\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);\n }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);\n return navigate;\n}\nconst OutletContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nfunction useOutletContext() {\n return React.useContext(OutletContext);\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nfunction useOutlet(context) {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return /*#__PURE__*/React.createElement(OutletContext.Provider, {\n value: context\n }, outlet);\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nfunction useParams() {\n let {\n matches\n } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? routeMatch.params : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nfunction useResolvedPath(to, _temp2) {\n let {\n relative\n } = _temp2 === void 0 ? {} : _temp2;\n let {\n future\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === \"path\"), [to, routePathnamesJson, locationPathname, relative]);\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nfunction useRoutes(routes, locationArg) {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nfunction useRoutesImpl(routes, locationArg, dataRouterState, future) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useRoutes() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches: parentMatches\n } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n if (process.env.NODE_ENV !== \"production\") {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = parentRoute && parentRoute.path || \"\";\n warningOnce(parentPathname, !parentRoute || parentPath.endsWith(\"*\"), \"You rendered descendant (or called `useRoutes()`) at \" + (\"\\\"\" + parentPathname + \"\\\" (under ) but the \") + \"parent route path has no trailing \\\"*\\\". This means if you navigate \" + \"deeper, the parent won't match anymore and therefore the child \" + \"routes will never render.\\n\\n\" + (\"Please change the parent to .\"));\n }\n let locationFromContext = useLocation();\n let location;\n if (locationArg) {\n var _parsedLocationArg$pa;\n let parsedLocationArg = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n !(parentPathnameBase === \"/\" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"When overriding the location using `` or `useRoutes(routes, location)`, \" + \"the location pathname must begin with the portion of the URL pathname that was \" + (\"matched by all parent routes. The current pathname base is \\\"\" + parentPathnameBase + \"\\\" \") + (\"but pathname \\\"\" + parsedLocationArg.pathname + \"\\\" was given in the `location` prop.\")) : UNSAFE_invariant(false) : void 0;\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n let pathname = location.pathname || \"/\";\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n let matches = matchRoutes(routes, {\n pathname: remainingPathname\n });\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(parentRoute || matches != null, \"No routes matched location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \") : void 0;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, \"Matched leaf route at location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \" + \"does not have an element or Component. This means it will render an with a \" + \"null value by default resulting in an \\\"empty\\\" page.\") : void 0;\n }\n let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),\n pathnameBase: match.pathnameBase === \"/\" ? parentPathnameBase : joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])\n })), parentMatches, dataRouterState, future);\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return /*#__PURE__*/React.createElement(LocationContext.Provider, {\n value: {\n location: _extends({\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\"\n }, location),\n navigationType: Action.Pop\n }\n }, renderedMatches);\n }\n return renderedMatches;\n}\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error) ? error.status + \" \" + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = {\n padding: \"0.5rem\",\n backgroundColor: lightgrey\n };\n let codeStyles = {\n padding: \"2px 4px\",\n backgroundColor: lightgrey\n };\n let devInfo = null;\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error handled by React Router default ErrorBoundary:\", error);\n devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"p\", null, \"\\uD83D\\uDCBF Hey developer \\uD83D\\uDC4B\"), /*#__PURE__*/React.createElement(\"p\", null, \"You can provide a way better UX than this when your app throws errors by providing your own \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"ErrorBoundary\"), \" or\", \" \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"errorElement\"), \" prop on your route.\"));\n }\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"h2\", null, \"Unexpected Application Error!\"), /*#__PURE__*/React.createElement(\"h3\", {\n style: {\n fontStyle: \"italic\"\n }\n }, message), stack ? /*#__PURE__*/React.createElement(\"pre\", {\n style: preStyles\n }, stack) : null, devInfo);\n}\nconst defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);\nclass RenderErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error\n };\n }\n static getDerivedStateFromError(error) {\n return {\n error: error\n };\n }\n static getDerivedStateFromProps(props, state) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (state.location !== props.location || state.revalidation !== \"idle\" && props.revalidation === \"idle\") {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation\n };\n }\n componentDidCatch(error, errorInfo) {\n console.error(\"React Router caught the following error during render\", error, errorInfo);\n }\n render() {\n return this.state.error !== undefined ? /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: this.props.routeContext\n }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {\n value: this.state.error,\n children: this.props.component\n })) : this.props.children;\n }\n}\nfunction RenderedRoute(_ref) {\n let {\n routeContext,\n match,\n children\n } = _ref;\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n return /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: routeContext\n }, children);\n}\nfunction _renderMatches(matches, parentMatches, dataRouterState, future) {\n var _dataRouterState;\n if (parentMatches === void 0) {\n parentMatches = [];\n }\n if (dataRouterState === void 0) {\n dataRouterState = null;\n }\n if (future === void 0) {\n future = null;\n }\n if (matches == null) {\n var _future;\n if (!dataRouterState) {\n return null;\n }\n if (dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches;\n } else if ((_future = future) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {\n // Don't bail if we're initializing with partial hydration and we have\n // router matches. That means we're actively running `patchRoutesOnNavigation`\n // so we should render down the partial matches to the appropriate\n // `HydrateFallback`. We only do this if `parentMatches` is empty so it\n // only impacts the root matches for `RouterProvider` and no descendant\n // ``\n matches = dataRouterState.matches;\n } else {\n return null;\n }\n }\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== undefined);\n !(errorIndex >= 0) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"Could not find a matching route for errors on route IDs: \" + Object.keys(errors).join(\",\")) : UNSAFE_invariant(false) : void 0;\n renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n if (match.route.id) {\n let {\n loaderData,\n errors\n } = dataRouterState;\n let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error;\n let shouldRenderHydrateFallback = false;\n let errorElement = null;\n let hydrateFallbackElement = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\"route-fallback\", false, \"No `HydrateFallback` element provided to render during initial hydration\");\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = /*#__PURE__*/React.createElement(match.route.Component, null);\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return /*#__PURE__*/React.createElement(RenderedRoute, {\n match: match,\n routeContext: {\n outlet,\n matches,\n isDataRoute: dataRouterState != null\n },\n children: children\n });\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {\n location: dataRouterState.location,\n revalidation: dataRouterState.revalidation,\n component: errorElement,\n error: error,\n children: getChildren(),\n routeContext: {\n outlet: null,\n matches,\n isDataRoute: true\n }\n }) : getChildren();\n }, null);\n}\nvar DataRouterHook = /*#__PURE__*/function (DataRouterHook) {\n DataRouterHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterHook[\"UseNavigateStable\"] = \"useNavigate\";\n return DataRouterHook;\n}(DataRouterHook || {});\nvar DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {\n DataRouterStateHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterStateHook[\"UseLoaderData\"] = \"useLoaderData\";\n DataRouterStateHook[\"UseActionData\"] = \"useActionData\";\n DataRouterStateHook[\"UseRouteError\"] = \"useRouteError\";\n DataRouterStateHook[\"UseNavigation\"] = \"useNavigation\";\n DataRouterStateHook[\"UseRouteLoaderData\"] = \"useRouteLoaderData\";\n DataRouterStateHook[\"UseMatches\"] = \"useMatches\";\n DataRouterStateHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterStateHook[\"UseNavigateStable\"] = \"useNavigate\";\n DataRouterStateHook[\"UseRouteId\"] = \"useRouteId\";\n return DataRouterStateHook;\n}(DataRouterStateHook || {});\nfunction getDataRouterConsoleError(hookName) {\n return hookName + \" must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.\";\n}\nfunction useDataRouterContext(hookName) {\n let ctx = React.useContext(DataRouterContext);\n !ctx ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return ctx;\n}\nfunction useDataRouterState(hookName) {\n let state = React.useContext(DataRouterStateContext);\n !state ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return state;\n}\nfunction useRouteContext(hookName) {\n let route = React.useContext(RouteContext);\n !route ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n !thisRoute.route.id ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, hookName + \" can only be used on routes that contain a unique \\\"id\\\"\") : UNSAFE_invariant(false) : void 0;\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nfunction useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nfunction useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nfunction useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(() => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation\n }), [dataRouterContext.router.revalidate, state.revalidation]);\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nfunction useMatches() {\n let {\n matches,\n loaderData\n } = useDataRouterState(DataRouterStateHook.UseMatches);\n return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nfunction useLoaderData() {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n if (state.errors && state.errors[routeId] != null) {\n console.error(\"You cannot `useLoaderData` in an errorElement (routeId: \" + routeId + \")\");\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nfunction useRouteLoaderData(routeId) {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nfunction useActionData() {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nfunction useRouteError() {\n var _state$errors;\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `` value\n */\nfunction useAsyncValue() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `` value\n */\nfunction useAsyncError() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._error;\n}\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nfunction useBlocker(shouldBlock) {\n let {\n router,\n basename\n } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(arg => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = arg;\n return shouldBlock({\n currentLocation: _extends({}, currentLocation, {\n pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname\n }),\n nextLocation: _extends({}, nextLocation, {\n pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname\n }),\n historyAction\n });\n }, [basename, shouldBlock]);\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable() {\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, _extends({\n fromRouteId: id\n }, options));\n }\n }, [router, id]);\n return navigate;\n}\nconst alreadyWarned$1 = {};\nfunction warningOnce(key, cond, message) {\n if (!cond && !alreadyWarned$1[key]) {\n alreadyWarned$1[key] = true;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, message) : void 0;\n }\n}\n\nconst alreadyWarned = {};\nfunction warnOnce(key, message) {\n if (process.env.NODE_ENV !== \"production\" && !alreadyWarned[message]) {\n alreadyWarned[message] = true;\n console.warn(message);\n }\n}\nconst logDeprecation = (flag, msg, link) => warnOnce(flag, \"\\u26A0\\uFE0F React Router Future Flag Warning: \" + msg + \". \" + (\"You can use the `\" + flag + \"` future flag to opt-in early. \") + (\"For more information, see \" + link + \".\"));\nfunction logV6DeprecationWarnings(renderFuture, routerFuture) {\n if ((renderFuture == null ? void 0 : renderFuture.v7_startTransition) === undefined) {\n logDeprecation(\"v7_startTransition\", \"React Router will begin wrapping state updates in `React.startTransition` in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\");\n }\n if ((renderFuture == null ? void 0 : renderFuture.v7_relativeSplatPath) === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {\n logDeprecation(\"v7_relativeSplatPath\", \"Relative route resolution within Splat routes is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\");\n }\n if (routerFuture) {\n if (routerFuture.v7_fetcherPersist === undefined) {\n logDeprecation(\"v7_fetcherPersist\", \"The persistence behavior of fetchers is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\");\n }\n if (routerFuture.v7_normalizeFormMethod === undefined) {\n logDeprecation(\"v7_normalizeFormMethod\", \"Casing of `formMethod` fields is being normalized to uppercase in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\");\n }\n if (routerFuture.v7_partialHydration === undefined) {\n logDeprecation(\"v7_partialHydration\", \"`RouterProvider` hydration behavior is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\");\n }\n if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n logDeprecation(\"v7_skipActionErrorRevalidation\", \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\");\n }\n }\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nfunction RouterProvider(_ref) {\n let {\n fallbackElement,\n router,\n future\n } = _ref;\n let [state, setStateImpl] = React.useState(router.state);\n let {\n v7_startTransition\n } = future || {};\n let setState = React.useCallback(newState => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n }, [setStateImpl, v7_startTransition]);\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n React.useEffect(() => {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, \"`` is deprecated when using \" + \"`v7_partialHydration`, use a `HydrateFallback` component instead\") : void 0;\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n let navigator = React.useMemo(() => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: n => router.navigate(n),\n push: (to, state, opts) => router.navigate(to, {\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n }),\n replace: (to, state, opts) => router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n })\n };\n }, [router]);\n let basename = router.basename || \"/\";\n let dataRouterContext = React.useMemo(() => ({\n router,\n navigator,\n static: false,\n basename\n }), [router, navigator, basename]);\n React.useEffect(() => logV6DeprecationWarnings(future, router.future), [router, future]);\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a ' : ''}\n`\n}\n","import { useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { ymd, sundayOf, addDays, driverLabel } from '../../lib/schedules'\nimport { buildScheduleHtml } from '../../lib/schedulePrint'\nimport { Button } from '../ui'\nimport { X } from 'lucide-react'\n\n// Print chooser → opens a clean, black-and-white printable schedule (browser Print / Save as PDF). No colors, no\n// on/off checkboxes — just people, days, dates and times.\n//\n// TWO LAYOUTS, because they serve two different readers (Brian, 2026-07-23):\n// • by person — one section per driver, their weeks underneath. What you hand to an individual.\n// • by day — one block per DATE listing everyone working it, earliest start first. This is the one the manager\n// prints and posts on the wall, and it is the more important of the two: a driver can pull up their\n// own schedule on the computer, but nobody reads a per-person printout on a wall to answer \"who is\n// in on Thursday\". Ordering by start time is the whole point — the wall is read as a timeline.\nexport default function PrintSchedule({ profile, people, initialPersonId, onClose }) {\n const [picked, setPicked] = useState(() => new Set(initialPersonId ? [initialPersonId] : []))\n const [fromWeek, setFromWeek] = useState(() => sundayOf())\n const [weeksCount, setWeeksCount] = useState(2)\n const [layout, setLayout] = useState('driver')\n const [busy, setBusy] = useState(false)\n\n // Switching to the wall layout selects everyone. A by-day sheet showing one person is not a thing anyone wants —\n // the question it answers is \"who is working\", so an empty or single-name roster is a broken printout, not a choice.\n // Still fully de-selectable afterwards if a manager really does want a subset.\n function changeLayout(next) {\n setLayout(next)\n if (next === 'day') setPicked(new Set(people.map(p => p.id)))\n }\n\n const allOn = people.length > 0 && picked.size === people.length\n const toggle = (id) => setPicked(p => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n })\n const toggleAll = () => setPicked(allOn ? new Set() : new Set(people.map(p => p.id)))\n\n async function generate() {\n if (picked.size === 0) return\n setBusy(true)\n const ids = [...picked]\n const starts = Array.from({ length: weeksCount }, (_, i) => addDays(fromWeek, i * 7))\n const startYmds = starts.map(ymd)\n\n // Keyed by EMPLOYEE, because `ids` are now people and not driver cards — somebody with no card has no driver_id\n // to match on, and matching on one would have printed them a blank week rather than failing visibly.\n const { data } = await supabase.from('driver_schedules').select('employee_id, week_start, days')\n .eq('org_id', profile.org_id).in('employee_id', ids).in('week_start', startYmds)\n const saved = {}\n for (const r of data || []) (saved[r.employee_id] = saved[r.employee_id] || {})[r.week_start] = r.days\n\n const chosen = people.filter(p => picked.has(p.id))\n const html = buildScheduleHtml({\n orgName: profile?.organizations?.name,\n people: chosen, starts, saved, layout,\n })\n\n const w = window.open('', '_blank')\n if (w) { w.document.write(html); w.document.close() }\n setBusy(false)\n onClose()\n }\n\n return (\n
\n
e.stopPropagation()} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '16px', width: '100%', maxWidth: '520px', padding: '1.75rem 2rem' }}>\n
\n

Print Schedules

\n \n
\n\n {/* Layout first — it changes what the other choices mean, so it reads before them rather than tucked at the end. */}\n \n\n {/* Range */}\n
\n \n \n
\n\n {/* Driver selection */}\n
\n {layout === 'day' ? 'Who to include' : 'Who to print'}\n \n
\n
\n {people.length === 0 &&
Nobody is on the schedule.
}\n {people.map(d => (\n \n ))}\n
\n\n
\n \n \n
\n

\n Opens a print-ready, black-and-white schedule. Use your browser's “Save as PDF” to keep a copy.\n {layout === 'day' && ' One week per page, each day listing who works it earliest-first.'}\n

\n
\n
\n )\n}\n\nconst ctl = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '8px', padding: '9px 12px', color: 'var(--text)', fontSize: '15px', outline: 'none' }\n","import { useEffect, useMemo, useRef, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { SCHED_DAYS, DAY_LABEL, DAY_OFFSET, defaultDays, ymd, sundayOf, addDays, weekNumber, dayHours, saveSchedule, savePersonDefault, driverLabel } from '../../lib/schedules'\nimport { planRegularCarry, clearSavedEdits } from '../../lib/scheduleEdits'\nimport { Button } from '../ui'\n\nconst SPAN = 2 // weeks on screen — the two-week view Brian asked for (2026-10-22)\nconst clone = (o) => JSON.parse(JSON.stringify(o))\n\n// EVERYONE, TWO WEEKS AT A TIME (Brian, 2026-10-22: \"a biweekly view so I can see what employees are working on what\n// days\"), and EDITABLE IN PLACE (same day: \"make our data points just like they are when you're looking at the person\n// view\"). Every cell carries the person view's own controls — start, end, Off — so a manager filling in next week\n// does it across the whole team without opening seven people one at a time.\n//\n// ONE WRITER, THE SAME ONE. A changed cell marks that person's WHOLE week dirty, and Save writes it through\n// saveSchedule — the exact call the person view's Save makes, a full-week row keyed to the employee. Each cell\n// resolves exactly as the editor does: that week's saved row, else the person's default week, else 8–4. So an edit\n// here and an edit there are indistinguishable in the database. What this view does NOT do is the person view's\n// \"Default — apply Week 1 to all weeks\" switch; that is a per-person rule and stays on the person's own page.\n//\n// TWO WAYS TO SAVE (Brian, 2026-10-22: \"is this a temporary change or a schedule change\"):\n// • This week only — writes the changed week rows and nothing else. Their regular week is untouched, so the week\n// after goes back to normal by itself.\n// • Regular schedule — the same week rows, PLUS the changed DAYS written into the person's default week\n// (savePersonDefault, the person view's own call), PLUS those same days carried into any LATER week that already\n// has its own saved row. Without that last step a later saved week would keep the old hours and the \"permanent\"\n// change would quietly not apply there. Only the edited days are carried: a later week's other one-off\n// differences (a short Friday, say) are someone's deliberate exception and survive. EACH CHANGE CARRIES ONLY\n// FROM ITS OWN WEEK FORWARD — see scheduleEdits.planRegularCarry, which replaced a carry from the earliest\n// edited week that backdated a week-5 change into weeks 2–4.\n//\n// Approved time off is shown on the cell (\"PTO\", or \"PTO?\" while pending) on top of the shift, not instead of it:\n// the shift is still editable, and the badge is what tells the manager not to count on that person that day.\nexport default function TeamSchedule({ profile, people, onPick, onDefaultSaved }) {\n const [from, setFrom] = useState(() => sundayOf())\n const [saved, setSaved] = useState(null) // { [employeeId]: { [weekStart]: days } } — what the database holds\n const [edits, setEdits] = useState({}) // { [employeeId]: { [weekStart]: days } } — changed, not yet saved\n const [changed, setChanged] = useState({}) // { [employeeId]: { [weekStart]: [dayKey, …] } } — which days were touched\n const [defaults, setDefaults] = useState({}) // { [employeeId]: days } — regular weeks saved here this visit\n const [pto, setPto] = useState([])\n const [saving, setSaving] = useState(false)\n const [savedMsg, setSavedMsg] = useState(false)\n const [saveError, setSaveError] = useState(null)\n\n // The edits as last rendered, for the post-save clear: see saveAll.\n const editsRef = useRef(edits)\n editsRef.current = edits\n\n const starts = useMemo(() => Array.from({ length: SPAN }, (_, i) => addDays(from, i * 7)), [from])\n const dirtyCount = Object.values(edits).reduce((n, w) => n + Object.keys(w).length, 0)\n\n // Loads the weeks on screen into `saved`, merged rather than replaced, so stepping back and forth keeps what was\n // fetched and — more importantly — keeps unsaved edits (they live in `edits`, keyed by week, untouched here).\n useEffect(() => {\n if (!profile?.org_id || !people.length) return\n let active = true\n const startYmds = starts.map(ymd)\n const lastDay = ymd(addDays(from, SPAN * 7 - 1))\n // Rows by person AND card-only rows by driver card: a week saved against the card before it was linked to the\n // employee has no employee_id, and read by employee alone it showed the default instead of what was saved.\n // A person's own row wins over a card-only one (the next save merges them — schedules.saveSchedule).\n const empIds = people.map(p => p.id)\n const cardOf = new Map(people.filter(p => p.driverId).map(p => [p.driverId, p.id]))\n const keyFilter = cardOf.size\n ? `employee_id.in.(${empIds.join(',')}),and(employee_id.is.null,driver_id.in.(${[...cardOf.keys()].join(',')}))`\n : `employee_id.in.(${empIds.join(',')})`\n Promise.all([\n supabase.from('driver_schedules').select('employee_id, driver_id, week_start, days')\n .eq('org_id', profile.org_id).or(keyFilter).in('week_start', startYmds),\n supabase.from('pto_requests').select('user_id, driver_id, start_date, end_date, status')\n .eq('org_id', profile.org_id).lte('start_date', lastDay).gte('end_date', ymd(from)),\n ]).then(([{ data: rows }, { data: reqs }]) => {\n if (!active) return\n setSaved(prev => {\n const m = { ...(prev || {}) }\n const own = (rows || []).filter(r => r.employee_id)\n const cardOnly = (rows || []).filter(r => !r.employee_id && cardOf.has(r.driver_id))\n for (const r of cardOnly) { const id = cardOf.get(r.driver_id); m[id] = { ...(m[id] || {}), [r.week_start]: r.days } }\n for (const r of own) m[r.employee_id] = { ...(m[r.employee_id] || {}), [r.week_start]: r.days }\n return m\n })\n setPto((reqs || []).filter(r => r.status !== 'denied'))\n })\n return () => { active = false }\n }, [profile?.org_id, people, from]) // eslint-disable-line react-hooks/exhaustive-deps\n\n const defaultOf = (p) => defaults[p.id] || p.default_schedule || defaultDays()\n const weekOf = (p, wsY) => edits[p.id]?.[wsY] || saved?.[p.id]?.[wsY] || defaultOf(p)\n\n function setCell(p, wsY, k, patch) {\n setSavedMsg(false); setSaveError(null)\n setEdits(prev => {\n const days = clone(weekOf(p, wsY))\n days[k] = { ...(days[k] || { start: '08:00', end: '16:00', off: false }), ...patch }\n return { ...prev, [p.id]: { ...(prev[p.id] || {}), [wsY]: days } }\n })\n setChanged(prev => {\n const keys = new Set(prev[p.id]?.[wsY] || []); keys.add(k)\n return { ...prev, [p.id]: { ...(prev[p.id] || {}), [wsY]: [...keys] } }\n })\n }\n\n // THE \"REGULAR SCHEDULE\" HALF, per person, planned from the edits as they were SENT (`sentEdits`/`sentChanged`).\n //\n // The later rows are read BEFORE the default is written: if that read fails, nothing has changed yet.\n // planRegularCarry decides every row — each day's change applies only from its own week forward, and the gap weeks\n // are written out so a change made in a later week cannot reach earlier ones through the new default.\n async function saveRegular(p, sentEdits, sentChanged) {\n const weeksEdited = Object.keys(sentEdits || {}).sort()\n if (!weeksEdited.length) return []\n // The person's rows, plus any card-only rows (written before the card was linked) — a gap week that already holds\n // one must be planned from it, not rewritten from the default over the top of it.\n const { data: later, error } = await supabase.from('driver_schedules').select('employee_id, week_start, days')\n .eq('org_id', profile.org_id).gt('week_start', weeksEdited[0])\n .or(p.driverId ? `employee_id.eq.${p.id},and(employee_id.is.null,driver_id.eq.${p.driverId})` : `employee_id.eq.${p.id}`)\n if (error) return [{ ok: false, error: `regular schedule not saved for ${driverLabel(p)}: ${error.message}` }]\n const { nextDefault, updates } = planRegularCarry({\n edits: sentEdits, changed: sentChanged || {}, oldDefault: defaultOf(p),\n // A person's own row wins over a card-only one for the same week (sorted so it is applied last).\n savedRows: [...(later || [])].sort((a, b) => (a.employee_id ? 1 : 0) - (b.employee_id ? 1 : 0)),\n })\n const results = [await savePersonDefault(profile.org_id, p, nextDefault)]\n if (results[0].ok) { setDefaults(prev => ({ ...prev, [p.id]: nextDefault })); onDefaultSaved?.(p.id, nextDefault) }\n const res = await Promise.all(updates.map(u => saveSchedule(profile.org_id, p, u.wsY, u.days)))\n const okUpdates = updates.filter((_, i) => res[i]?.ok)\n if (okUpdates.length) setSaved(prev => {\n const m = { ...(prev || {}) }\n m[p.id] = { ...(m[p.id] || {}) }\n for (const u of okUpdates) m[p.id][u.wsY] = u.days\n return m\n })\n return [...results, ...res]\n }\n\n // Same discipline as the person view's saveAll: every result is READ, and a failure keeps that week's edit on\n // screen marked unsaved rather than pretending it stuck. Weeks that did save leave the dirty set.\n async function saveAll(regular) {\n const jobs = []\n for (const p of people) for (const [wsY, days] of Object.entries(edits[p.id] || {})) jobs.push({ p, wsY, days })\n if (!jobs.length) return\n setSaving(true); setSaveError(null)\n // Snapshotted now: the regular-schedule plan is made from what was SENT, not from state that may move on.\n const sentEdits = edits, sentChanged = changed\n const results = await Promise.all(jobs.map(j => saveSchedule(profile.org_id, j.p, j.wsY, j.days)))\n // Recorded BEFORE the regular-schedule pass, which may rewrite one of these same weeks (an edited later week\n // takes an earlier week's change on the days it did not touch) — recorded after, it overwrote that on screen.\n const ok = jobs.filter((_, i) => results[i]?.ok)\n setSaved(prev => {\n const m = { ...(prev || {}) }\n for (const j of ok) m[j.p.id] = { ...(m[j.p.id] || {}), [j.wsY]: j.days }\n return m\n })\n // Regular-schedule writes run only for people whose week rows ALL saved: a regular week built from edits that did\n // not stick would disagree with the very weeks it came from.\n const extra = []\n if (regular) {\n for (const p of new Set(jobs.map(j => j.p))) {\n if (jobs.some((j, i) => j.p === p && !results[i]?.ok)) continue\n extra.push(...(await saveRegular(p, sentEdits[p.id], sentChanged[p.id])))\n }\n }\n setSaving(false)\n // ONLY WHAT WAS SAVED IS CLEARED. This deleted every saved week's edit by key, so a cell changed while the save\n // was in flight vanished from screen without being written. clearSavedEdits keeps any edit that is no longer the\n // very object that was sent. The inputs are also disabled while saving (below); this half holds regardless.\n setEdits(prev => clearSavedEdits(prev, {}, ok).edits)\n setChanged(prev => clearSavedEdits(editsRef.current, prev, ok).changed)\n const failed = results.find(r => !r?.ok)\n if (failed) { setSaveError(`${jobs.length - ok.length} of ${jobs.length} not saved — ${failed.error || 'try again'}`); return }\n const extraFailed = extra.find(r => !r?.ok)\n if (extraFailed) { setSaveError(`Weeks saved, but the regular schedule was not fully updated — ${extraFailed.error || 'try again'}`); return }\n setSavedMsg(regular ? 'regular' : 'week'); setTimeout(() => setSavedMsg(false), 3500)\n }\n\n function pick(id) {\n if (dirtyCount && !window.confirm('You have unsaved schedule changes. Leave without saving?')) return\n onPick(id)\n }\n\n const offFor = (p, dateYmd) => pto.find(r =>\n ((p.userId && r.user_id === p.userId) || (p.driverId && r.driver_id === p.driverId)) &&\n r.start_date <= dateYmd && r.end_date >= dateYmd)\n\n const today = ymd(new Date())\n const fmt = (d) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })\n\n return (\n
\n
\n
\n \n \n \n \n Sun {fmt(from)} – Sat {fmt(addDays(from, SPAN * 7 - 1))}\n \n
\n
\n {savedMsg && ✓ {savedMsg === 'regular' ? 'Saved as regular schedule' : 'Saved for this week'}}\n {saveError && ⚠ {saveError}}\n {dirtyCount > 0 && !saving && {dirtyCount} week{dirtyCount === 1 ? '' : 's'} changed}\n \n \n
\n
\n\n {saved === null ? (\n
Loading…
\n ) : starts.map(ws => {\n const wsY = ymd(ws)\n return (\n
\n
\n Week {weekNumber(ws)}\n Sun {fmt(ws)}\n
\n {/* Scrolls inside itself on a narrow screen: the page must never scroll sideways (nav goes out of reach). */}\n
\n \n \n \n \n {SCHED_DAYS.map(k => {\n const dY = ymd(addDays(ws, DAY_OFFSET[k]))\n return \n })}\n \n \n \n \n {people.map(p => {\n const days = weekOf(p, wsY)\n const dirty = !!edits[p.id]?.[wsY]\n const hours = SCHED_DAYS.reduce((s, k) => s + dayHours(days[k]), 0)\n return (\n \n \n {SCHED_DAYS.map(k => {\n const dateY = ymd(addDays(ws, DAY_OFFSET[k]))\n const day = days[k] || { start: '08:00', end: '16:00', off: false }\n const off = offFor(p, dateY)\n return (\n \n )\n })}\n \n \n )\n })}\n \n \n {SCHED_DAYS.map(k => {\n const dateY = ymd(addDays(ws, DAY_OFFSET[k]))\n const n = people.filter(p => { const d = weekOf(p, wsY)[k]; return d && !d.off && !offFor(p, dateY) }).length\n return \n })}\n \n \n
Person{DAY_LABEL[k]} {addDays(ws, DAY_OFFSET[k]).getDate()}Hours
\n \n {dirty &&
unsaved
}\n
\n
\n {off && {off.status === 'approved' ? 'PTO' : 'PTO?'}}\n {day.off ? (\n Off\n ) : (\n <>\n setCell(p, wsY, k, { start: e.target.value })} style={timeInput} />\n setCell(p, wsY, k, { end: e.target.value })} style={timeInput} />\n \n )}\n \n
\n
{Math.round(hours * 10) / 10}h
Working{n}\n
\n
\n
\n )\n })}\n

\n Change any shift, then save it for this week only (a one-off) or as their regular schedule (from now on). PTO = approved time off · PTO? = requested, not yet approved.\n Click a name for that person’s 4-week view and the Default (repeat every week) switch.\n

\n
\n )\n}\n\nconst th = { padding: '10px 8px', fontSize: '14px', fontWeight: 800, textAlign: 'center', whiteSpace: 'nowrap' }\nconst td = { padding: '8px 6px', fontSize: '15px', textAlign: 'center', whiteSpace: 'nowrap', verticalAlign: 'top' }\nconst timeInput = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '5px 6px', color: 'var(--text)', fontSize: '14px', fontWeight: 600, outline: 'none', width: '112px', colorScheme: 'dark light' }\n","import { useEffect, useRef, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { SCHED_DAYS, DAY_LABEL, DAY_OFFSET, defaultDays, ymd, sundayOf, addDays, weekNumber, getSchedule, saveSchedule, savePersonDefault, dayHours, driverLabel, getSchedulePeople } from '../../lib/schedules'\nimport ScheduleReport from './ScheduleReport'\nimport PrintSchedule from './PrintSchedule'\nimport TeamSchedule from './TeamSchedule'\nimport { formatPhone } from '../../lib/format'\nimport { sendRouteSms } from '../../lib/sendRoute'\nimport { weeksSnapshot } from '../../lib/scheduleEdits'\nimport { Button, Input } from '../ui'\nimport { X } from 'lucide-react'\n\nconst WEEKS = 4\nconst clone = (o) => JSON.parse(JSON.stringify(o))\n\nexport default function SchedulesScreen({ profile }) {\n const [people, setPeople] = useState([])\n const [personId, setPersonId] = useState(null)\n const [weeks, setWeeks] = useState([]) // [{ weekStart(Date), days, saved }]\n const [defaultOn, setDefaultOn] = useState(false)\n const [baseline, setBaseline] = useState(null) // weeksSnapshot of what was loaded / last saved — see `dirty`\n const [loading, setLoading] = useState(false)\n const [saving, setSaving] = useState(false)\n const [savedMsg, setSavedMsg] = useState(false)\n const [saveError, setSaveError] = useState(null)\n const [showReport, setShowReport] = useState(false)\n const [showPrint, setShowPrint] = useState(false)\n const [copied, setCopied] = useState(false)\n const [sharing, setSharing] = useState(null) // null | 'sending' | 'sent' | \n const [showDetails, setShowDetails] = useState(false)\n const [details, setDetails] = useState(null) // { legal_name, phone, email, home_address } for the selected driver\n const [savingDetails, setSavingDetails] = useState(false)\n const [detailsSaved, setDetailsSaved] = useState(false)\n const baseSunday = useRef(sundayOf())\n const [view, setView] = useState('person') // 'person' = edit one person's 4 weeks; 'team' = everyone, 2 weeks\n\n const person = people.find(p => p.id === personId) || null\n\n // THE PEOPLE ON THE SCHEDULE. Everyone whose employee record is ticked \"On the schedule\", with their driver card\n // attached if they have one — which some of them do not, and that is the whole point of the 2026-09-05 change.\n // Sara Meyer is hourly, punches the clock every working day and has no card; keyed to cards, this screen could not\n // show her at all. Who appears is now that tick, set in Settings → People, rather than a guess made from pay type.\n useEffect(() => {\n if (!profile?.org_id) return\n let cancelled = false\n getSchedulePeople(profile.org_id).then(list => {\n if (cancelled) return\n setPeople(list)\n if (list.length && !personId) setPersonId(list[0].id)\n })\n return () => { cancelled = true }\n }, [profile?.org_id]) // eslint-disable-line react-hooks/exhaustive-deps\n\n // Populate the details panel from the selected person. These fields live on the DRIVER card and are still written\n // there — `employees` has its own writer (saveEmployee, which handles the column-grant traps around login and PIN\n // fields), and a second writer of the same table is how two copies of one fact start to disagree. So the panel is\n // offered only to somebody who has a card, and Settings → People is where the rest are edited.\n useEffect(() => {\n if (!person) { setDetails(null); return }\n setDetails({ legal_name: person.legal_name || '', phone: formatPhone(person.phone || ''), email: person.email || '', address_line1: person.address_line1 || '', city: person.city || '', state: person.state || '', zip: person.zip || '' })\n setDetailsSaved(false)\n }, [personId, people]) // eslint-disable-line react-hooks/exhaustive-deps\n\n async function saveDetails() {\n if (!person?.driverId || !details) return\n setSavingDetails(true)\n const patch = {\n legal_name: details.legal_name.trim() || null,\n phone: details.phone.trim() || null,\n email: details.email.trim() || null,\n address_line1: details.address_line1.trim() || null,\n city: details.city.trim() || null,\n state: details.state.trim() || null,\n zip: details.zip.trim() || null,\n }\n const { data, error } = await supabase.from('drivers').update(patch).eq('id', person.driverId).select('id')\n setSavingDetails(false)\n if (error) { window.alert(`Could not save details: ${error.message}`); return }\n if (!data || data.length === 0) {\n window.alert(\"Couldn't save — the update didn't apply. If you're viewing another organization (View As, read-only), exit it and try again.\")\n return\n }\n setPeople(prev => prev.map(p => p.id === personId ? { ...p, ...patch } : p))\n setDetailsSaved(true)\n setShowDetails(false) // close on success so it's clear it saved\n }\n\n // Load the selected person's 4 weeks (each: its own saved schedule, else their default, else 8–4).\n //\n // RE-READ ON EVERY RETURN TO THIS VIEW, not only when the person changes (2026-10-26). The Everyone grid edits the\n // same rows; this used to load once per person, so after editing the grid and switching back it still showed the\n // weeks as they were BEFORE — and Save (enabled whether or not anything had changed) wrote those stale weeks back\n // over the grid's edits. `view` re-reads on return; `person.default_schedule` re-reads when a regular-schedule save\n // from the grid changes the default that unsaved weeks fall back to. Leaving with unsaved edits asks first\n // (leavePerson), so a re-read never silently drops work done here.\n useEffect(() => {\n if (!person || view !== 'person') return\n let active = true\n setLoading(true); setSavedMsg(false); setSaveError(null)\n const starts = Array.from({ length: WEEKS }, (_, i) => addDays(baseSunday.current, i * 7))\n Promise.all(starts.map(s => getSchedule(profile.org_id, person, ymd(s)))).then(results => {\n if (!active) return\n const fallback = person.default_schedule || defaultDays()\n const w = starts.map((s, i) => ({ weekStart: s, days: results[i] ? clone(results[i]) : clone(fallback), saved: !!results[i] }))\n // If weeks 2–4 already mirror week 1, reflect that the \"default\" link is on.\n const allMatch = w.every(x => JSON.stringify(x.days) === JSON.stringify(w[0].days))\n setWeeks(w)\n setDefaultOn(allMatch && w[0].saved)\n setBaseline(weeksSnapshot(w, allMatch && w[0].saved))\n setLoading(false)\n })\n return () => { active = false }\n }, [personId, view, person?.default_schedule]) // eslint-disable-line react-hooks/exhaustive-deps\n\n // SOMETHING TO SAVE. Save is disabled until the weeks or the Default switch differ from what was loaded or last\n // saved: an always-live Save is what let an untouched, stale screen overwrite newer rows. Null baseline = not\n // loaded yet, which is never dirty.\n const dirty = baseline !== null && !loading && weeksSnapshot(weeks, defaultOn) !== baseline\n // Switching person or view throws the on-screen weeks away (the load above replaces them), so ask first.\n const leavePerson = () => !dirty || window.confirm('You have unsaved schedule changes for this person. Leave without saving?')\n\n function setDay(weekIdx, k, patch) {\n setSavedMsg(false); setSaveError(null)\n setWeeks(prev => {\n const next = prev.map(w => ({ ...w, days: { ...w.days } }))\n next[weekIdx].days[k] = { ...(next[weekIdx].days[k] || {}), ...patch }\n // While \"default\" is on, week 1 drives the rest.\n if (defaultOn && weekIdx === 0) for (let i = 1; i < next.length; i++) next[i].days = clone(next[0].days)\n return next\n })\n }\n\n function toggleDefault() {\n const on = !defaultOn\n setDefaultOn(on); setSavedMsg(false); setSaveError(null)\n if (on) setWeeks(prev => prev.map((w, i) => i === 0 ? w : { ...w, days: clone(prev[0].days) }))\n }\n\n async function saveAll() {\n if (!person) return\n setSaving(true)\n const toSave = defaultOn ? weeks.map((w, i) => ({ ...w, days: i === 0 ? w.days : clone(weeks[0].days) })) : weeks\n // THE RESULTS ARE READ NOW. They were thrown away, and \"✓ Saved\" was shown unconditionally — so a rejected write\n // was indistinguishable from a successful one, and the screen went on displaying the hours it had failed to\n // store. Found on 2026-09-05 by a save that silently wrote nothing at all: the database refused the row and the\n // page said it had saved. A schedule is what somebody plans their week around; it must never claim to hold\n // something it does not.\n const results = await Promise.all(toSave.map(w => saveSchedule(profile.org_id, person, ymd(w.weekStart), w.days)))\n if (defaultOn) results.push(await savePersonDefault(profile.org_id, person, weeks[0].days))\n const failed = results.find(r => r && !r.ok)\n setSaving(false)\n if (failed) {\n setSaveError(failed.error || 'The schedule was not saved.')\n return\n }\n setSaveError(null); setSavedMsg(true)\n setWeeks(toSave.map(w => ({ ...w, saved: true })))\n setBaseline(weeksSnapshot(toSave, defaultOn))\n setTimeout(() => setSavedMsg(false), 3000)\n }\n\n const fmtDate = (d) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })\n\n // The shareable link to THIS driver's schedule. Built off the deployed origin so a link copied from a laptop works on\n // the phone it's pasted into — and off schedule_token, NEVER driver.id: the id is the /d/ route credential, which\n // hands over the live run (customer names, addresses, COD) and accepts writes. This link is meant to be forwarded.\n // Only somebody with a driver card has one: the token lives on `drivers`, and the /s/ page is served by\n // driver-route, which resolves a driver. Office staff have a login and see their week on the Time screen instead,\n // so they get no dead button here rather than a link that cannot be minted.\n const shareUrl = person?.schedule_token ? `${window.location.origin}/s/${person.schedule_token}` : ''\n async function copyShareLink() {\n if (!shareUrl) return\n try { await navigator.clipboard.writeText(shareUrl) } catch { /* clipboard blocked — the prompt below still shows it */ }\n setCopied(true); setTimeout(() => setCopied(false), 2500)\n }\n async function textShareLink() {\n if (!person?.phone || !shareUrl) return\n setSharing('sending')\n const who = driverLabel(person).split(' ')[0] || 'there'\n const org = profile?.organizations?.name || 'Route Now'\n const res = await sendRouteSms({\n phone: person.phone,\n driverName: driverLabel(person),\n // Carries the opt-out line itself: passing a custom `message` bypasses send-route's default template, and this is\n // a new recurring message class rather than a one-off route hand-off, so it needs it on 10DLC/TCPA grounds.\n message: `${org}: Hi ${who}, here's your work schedule — ${shareUrl}\\nIt stays up to date, so save the link.\\nReply STOP to opt out.`,\n })\n if (res?.error) setSharing(res.error)\n else { setSharing('sent'); setTimeout(() => setSharing(null), 4000) }\n }\n\n // REVOKE a schedule link. This link is built to be forwarded and kept, which is exactly why it needs a way to be\n // taken back: a driver who leaves, a phone that is lost, or a link pasted into the wrong thread otherwise keeps\n // returning that person's name and four weeks of when they are not at home, forever. Rotating the token is the\n // revocation — /s/:token resolves by exact match, so the old URL stops resolving the instant this lands.\n // Deliberately NOT reusing drivers.id: that is the /d/ route credential and is not rotatable at all.\n async function resetShareLink() {\n if (!person?.driverId || !profile?.org_id) return\n const who = driverLabel(person)\n if (!window.confirm(`Reset ${who}'s schedule link?\\n\\nThe link you sent before stops working straight away — anyone still holding it, including ${who}, will need the new one.`)) return\n setSharing('resetting')\n const next = (typeof crypto !== 'undefined' && crypto.randomUUID) ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`\n const { error } = await supabase.from('drivers')\n .update({ schedule_token: next }).eq('id', person.driverId).eq('org_id', profile.org_id)\n if (error) { setSharing(`Could not reset the link: ${error.message}`); return }\n setPeople((prev) => prev.map((p) => (p.id === personId ? { ...p, schedule_token: next } : p)))\n setSharing('reset'); setTimeout(() => setSharing(null), 6000)\n }\n\n return (\n
\n
\n
\n

Schedules

\n \n
\n \n
\n\n {/* WHICH VIEW. One person's four weeks is where schedules are edited; Everyone is the two-week, read-only grid\n of who works which day (Brian, 2026-10-22). */}\n
\n {[['person', 'One person · 4 weeks'], ['team', 'Everyone · 2 weeks']].map(([k, label]) => (\n \n ))}\n
\n\n {/* A regular-schedule save from the grid updates the person's default here too, so their 4-week view shows it\n without a reload (unsaved weeks fall back to that default). The grid re-reads its weeks when `people`\n changes and merges them, so nothing on screen is lost. */}\n {view === 'team' && { setPersonId(id); setView('person') }}\n onDefaultSaved={(id, days) => setPeople(prev => prev.map(p => (p.id === id ? { ...p, default_schedule: days } : p)))} />}\n\n {view === 'person' && <>\n {/* Person picker. Says \"Person\" rather than \"Driver\" because that is now what it holds: office staff belong on a\n schedule too, and the label was part of why nobody noticed they could not be put on one. */}\n
\n \n {people.length === 0 ? (\n Nobody is on the schedule yet — tick “On the schedule” on a person in Settings → People.\n ) : (\n \n )}\n {/* THE CARD-ONLY CONTROLS. Details edits fields that live on the driver card, and the share link is minted\n from a token that lives there too — so both are offered only to somebody who has one. Hidden rather than\n disabled: a greyed-out button invites a click and then explains itself, and there is nothing to explain\n here beyond \"this person is not a driver\". */}\n {person?.driverId && (\n <>\n \n {/* SHARE — drivers have no account to sign into, so a schedule they can only reach by logging in is one they\n never see. The link is live (it re-reads on open), so a shift change doesn't need re-sending. Office\n staff do have a login, and their week shows on the Time screen. */}\n \n \n \n {sharing === 'reset' && ✓ Old link is dead — copy or text the new one}\n {sharing && !['sending', 'sent', 'resetting', 'reset'].includes(sharing) && {sharing}}\n \n )}\n
\n\n {person && details && (\n <>\n {/* Default link + Save */}\n
\n \n
\n {savedMsg && ✓ Saved}\n {saveError && ⚠ Not saved — {saveError}}\n \n
\n
\n\n {loading ? (\n
Loading…
\n ) : (\n // Grid floor capped by min(100%, N): a card can never demand more width than the screen has. A bare Npx\n // floor made the whole page scroll sideways on a phone, which carries the nav out of reach.\n
\n {weeks.map((w, i) => {\n const mirrored = defaultOn && i > 0\n const weekHours = SCHED_DAYS.reduce((s, k) => s + dayHours(w.days[k]), 0)\n return (\n
\n
\n
\n Week {weekNumber(w.weekStart)}\n {i === 0 && Current}\n {mirrored && Following Week 1}\n
\n Sun {fmtDate(w.weekStart)} · {Math.round(weekHours * 10) / 10}h\n
\n\n
\n {SCHED_DAYS.map(k => {\n const day = w.days[k] || { start: '08:00', end: '16:00', off: false }\n const date = addDays(w.weekStart, DAY_OFFSET[k])\n return (\n
\n {DAY_LABEL[k]} {date.getDate()}\n {day.off ? (\n Off\n ) : (\n \n setDay(i, k, { start: e.target.value })} style={timeInput} />\n –\n setDay(i, k, { end: e.target.value })} style={timeInput} />\n \n )}\n \n
\n )\n })}\n
\n
\n )\n })}\n
\n )}\n \n )}\n }\n\n {showReport && setShowReport(false)} />}\n {showPrint && setShowPrint(false)} />}\n\n {/* Details — tucked behind the ✎ Details button so the schedule sits up top. Legal name & home address live only\n here; phone & email are shared with the driver card. */}\n {showDetails && person?.driverId && details && (\n
setShowDetails(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 3600, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '2.5rem 1rem', overflowY: 'auto' }}>\n
e.stopPropagation()} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '16px', width: '100%', maxWidth: '560px', padding: '1.75rem 2rem' }}>\n
\n

{driverLabel(person)} · Details

\n \n
\n
\n { setDetails(p => ({ ...p, legal_name: v })); setDetailsSaved(false) }} placeholder=\"e.g. Susan Way\" />\n { setDetails(p => ({ ...p, address_line1: v })); setDetailsSaved(false) }} placeholder=\"123 Main St\" />\n
\n { setDetails(p => ({ ...p, city: v })); setDetailsSaved(false) }} placeholder=\"Fenton\" />\n { setDetails(p => ({ ...p, state: v.toUpperCase().slice(0, 2) })); setDetailsSaved(false) }} placeholder=\"MO\" />\n { setDetails(p => ({ ...p, zip: v.replace(/[^\\d-]/g, '').slice(0, 10) })); setDetailsSaved(false) }} placeholder=\"63026\" />\n
\n
\n { setDetails(p => ({ ...p, phone: formatPhone(v) })); setDetailsSaved(false) }} placeholder=\"555-123-4567\" hint=\"shared with driver card\" />\n { setDetails(p => ({ ...p, email: v })); setDetailsSaved(false) }} placeholder=\"name@email.com\" hint=\"shared with driver card\" />\n
\n
\n
\n {detailsSaved && ✓ Saved}\n \n \n
\n
\n
\n )}\n
\n )\n}\n\nconst timeInput = {\n flex: 1, minWidth: 0, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '8px',\n padding: '9px 11px', color: 'var(--text)', fontSize: '16px', fontWeight: 600, outline: 'none',\n}\n\nfunction Field({ label, value, onChange, placeholder, type, hint }) {\n return (\n \n )\n}\n","import { useMemo, useState } from 'react'\nimport { updatePunch, addPunch, deletePunch, pairShiftsDetailed, windowedMs } from '../../lib/timeclock'\nimport { Card, Button, Input } from '../ui'\nimport { localDayStartMs, localDayEndMs } from '../../lib/format'\n\n// ADMIN PUNCH CORRECTIONS. Day one of a real time clock produces forgotten punches, late punches and wrong-day\n// punches — an admin has to be able to fix them or the payroll numbers are wrong from the first week.\n//\n// Deliberately shows the raw punches rather than just the paired totals: when someone forgets to clock out, the\n// total is meaningless and what the admin needs to see is the single dangling 'in'. Corrections are visibly marked\n// (edited / added by hand) because a payroll record that can be changed invisibly is worse than one that cannot be\n// changed at all.\n\nconst ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\nconst fmtHrs = (ms) => `${Math.round((ms / 3600000) * 100) / 100}`\nconst clock = (iso) => new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\nconst dayLabel = (key) => new Date(key + 'T12:00:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })\n\n// wants local wall time with no zone; the DB stores UTC.\nconst toLocalInput = (iso) => {\n const d = new Date(iso)\n return `${ymd(d)}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`\n}\nconst fromLocalInput = (v) => (v ? new Date(v).toISOString() : null)\n\n// `roster` is getPeopleOptions' list ({ id, name, kind: 'user' | 'driver', archived }). The per-person \"+ Add punch\"\n// only exists for someone who already has a punch this week, so a person who never clocked in at all had no row to\n// add one from (Faith, 2026-10-28). The \"Add a punch for…\" picker at the top reaches anyone on the time clock.\nexport default function PunchEditor({ events, names, roster = [], orgId, editedBy, weekStart, onChange }) {\n const [editing, setEditing] = useState(null) // punch id\n const [draft, setDraft] = useState({ at: '', kind: 'in', note: '' })\n const [adding, setAdding] = useState(null) // person key\n const [pickFor, setPickFor] = useState('') // roster id for the \"Add a punch for…\" picker\n const [busy, setBusy] = useState(false)\n const [err, setErr] = useState(null)\n\n // The events arrive with a day of margin either side of the week so boundary-spanning shifts can pair; the margin\n // days themselves display in THEIR week's view, not this one.\n const weekFromKey = ymd(weekStart)\n const weekToKey = ymd(new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate() + 7))\n const weekEndMs = new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate() + 7).getTime()\n\n // A punch identifies its person by user_id (staff) OR driver_id (drivers, who have no login at all). Grouping on\n // user_id alone silently merged every driver into one nameless bucket.\n const people = useMemo(() => {\n const g = {}\n for (const e of events) {\n const key = e.user_id || e.driver_id\n if (!key) continue\n ;(g[key] = g[key] || []).push(e)\n }\n const capMs = Math.min(Date.now(), weekEndMs)\n return Object.entries(g)\n .map(([key, ev]) => {\n const sorted = [...ev].sort((a, b) => a.at.localeCompare(b.at))\n // Pair the WHOLE loaded range once, then flag the punches that paired with nothing. Pairing day by day\n // flagged both halves of a legit overnight shift as \"missing a punch\". A shift someone is still ON is not a\n // problem, so the chronologically-last punch gets a pass even as an orphan 'in' (a mid-shift double-tap).\n const { orphans } = pairShiftsDetailed(sorted, capMs)\n const lastId = sorted[sorted.length - 1]?.id\n return {\n key,\n isDriver: !ev[0].user_id,\n name: names[key] || 'Unknown',\n events: sorted,\n ms: windowedMs(sorted, weekStart.getTime(), weekEndMs, capMs),\n flagged: new Set(orphans.filter(o => o.kind === 'out' || o.id !== lastId).map(o => o.id)),\n }\n })\n .filter(p => p.events.some(e => { const k = ymd(new Date(e.at)); return k >= weekFromKey && k < weekToKey }))\n .sort((a, b) => a.name.localeCompare(b.name))\n }, [events, names, weekStart, weekEndMs, weekFromKey, weekToKey])\n\n async function run(fn) {\n setBusy(true); setErr(null)\n const r = await fn()\n setBusy(false)\n if (r?.error) { setErr(r.error); return false }\n setEditing(null); setAdding(null); setPickFor('')\n onChange?.()\n return true\n }\n\n function startEdit(p) {\n setErr(null); setEditing(p.id)\n setDraft({ at: toLocalInput(p.at), kind: p.kind, note: p.edit_note || '' })\n }\n\n function startAdd(person) {\n setErr(null); setPickFor(''); setAdding(person.key)\n setDraft({ at: `${ymd(weekStart)}T08:00`, kind: 'in', note: '' })\n }\n\n // The same In/Out · time · reason · Add row the per-person form uses, filed against whoever `person` is.\n const addRow = (person) => (\n <>\n \n setDraft(d => ({ ...d, at: e.target.value }))} style={selectStyle} />\n setDraft(d => ({ ...d, note: e.target.value }))} placeholder=\"Reason (optional)\" style={{ flex: '1 1 160px' }} />\n \n \n )\n\n const picked = roster.find(r => r.id === pickFor)\n const pickedPerson = picked ? { key: picked.id, name: picked.name, isDriver: picked.kind === 'driver' } : null\n const pickerRow = roster.length > 0 && (\n
\n Add a punch for\n { setErr(null); setAdding(null); setPickFor(e.target.value); setDraft({ at: `${ymd(weekStart)}T08:00`, kind: 'in', note: '' }) }}\n style={selectStyle}\n >\n \n {roster.filter(r => !r.archived).map(r => )}\n \n {pickedPerson && (\n <>\n {addRow(pickedPerson)}\n \n \n )}\n
\n )\n\n if (!people.length) {\n return (\n \n

Punches

\n {err &&
{err}
}\n {pickerRow}\n
No punches recorded this week.
\n
\n )\n }\n\n return (\n \n

Punches

\n
\n Fix a wrong time, add a punch someone forgot, or remove one that should not be there. Every correction is\n recorded against your name and keeps the original time.\n
\n {err &&
{err}
}\n {pickerRow}\n\n {people.map(person => {\n const byDay = {}\n for (const e of person.events) {\n const k = ymd(new Date(e.at))\n if (k < weekFromKey || k >= weekToKey) continue // margin days pair here but display in their own week\n ;(byDay[k] = byDay[k] || []).push(e)\n }\n return (\n
\n {/* Everything about a person sits together on the left. Pushing the total to the far edge with\n space-between stranded a number several inches from the name it belonged to, and put the action\n furthest from the thing it acts on. Name, then the action, then the total, reading order. */}\n
\n {person.name}\n {person.isDriver && driver}\n \n \n {fmtHrs(person.ms)} hrs this week\n \n
\n\n {Object.entries(byDay).sort(([a], [b]) => a.localeCompare(b)).map(([day, list]) => {\n // A punch on this day paired with nothing — a missing in or out, the exact case this screen exists\n // for. Odd-count-per-day was the old test, and it flagged both days of every legit overnight shift.\n const incomplete = list.some(p => person.flagged.has(p.id))\n // Per-day total, clipped to that day. Pairing is done over the person's WHOLE stream (an overnight shift\n // pairs across midnight); only the clip is per day, so the day figures still sum to the week header.\n //\n // Clipped to the NEXT LOCAL MIDNIGHT, not dayFrom + 24h (2026-10-26). A DST day is 23 or 25 hours: on\n // 2026-11-01 the fixed 24h window stopped an hour short of midnight and the next day's window started an\n // hour early, so an hour worked late that night counted on BOTH days — and in spring an hour fell in\n // neither. localDayEndMs builds the next midnight with the Date constructor, so the days tile exactly.\n const dayFrom = localDayStartMs(day)\n const dayMs = windowedMs(person.events, dayFrom, localDayEndMs(day), Math.min(Date.now(), weekEndMs))\n return (\n
\n
\n {dayLabel(day)}\n {dayMs > 0 && {fmtHrs(dayMs)}}\n {incomplete && ⚠ missing a punch}\n
\n {list.map(p => (\n
\n {editing === p.id ? (\n <>\n \n setDraft(d => ({ ...d, at: e.target.value }))} style={selectStyle} />\n setDraft(d => ({ ...d, note: e.target.value }))} placeholder=\"Reason (optional)\" style={{ flex: '1 1 160px' }} />\n \n \n \n ) : (\n <>\n \n {p.kind === 'in' ? 'IN' : 'OUT'}\n \n {clock(p.at)}\n \n { if (window.confirm(`Delete this ${p.kind === 'in' ? 'clock-in' : 'clock-out'} at ${clock(p.at)}? This cannot be undone.`)) run(() => deletePunch(p.id, { person: person.name, row: p })) }}\n style={{ ...linkBtn, color: '#fca5a5' }}\n >Delete\n {/* Metadata badges trail AFTER the actions, with a fixed-width IN/OUT and time before them, so\n IN/OUT · time · Edit · Delete line up as columns on every row whether or not a punch carries a\n badge. Before this the \"added by hand\" badge sat between the time and the actions and shoved\n Edit/Delete around row to row — which read as \"the columns are all off\" (Brian, 07-23). */}\n {p.manual && added by hand}\n {p.edited_at && !p.manual && (\n \n edited{p.original_at ? ` · was ${clock(p.original_at)}` : ''}\n \n )}\n {p.edit_note && {p.edit_note}}\n \n )}\n
\n ))}\n
\n )\n })}\n\n {adding === person.key && (\n
\n {addRow(person)}\n \n
\n )}\n
\n )\n })}\n
\n )\n}\n\nconst linkBtn = { background: 'transparent', border: 'none', color: '#7dd3fc', fontSize: '13px', fontWeight: 700, cursor: 'pointer', padding: '2px 4px' }\nconst selectStyle = { background: 'var(--sunken)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: '6px', padding: '5px 8px', fontSize: '14px' }\nconst badge = { background: 'var(--sunken)', color: 'var(--text-2)', border: '1px solid var(--border)', borderRadius: '999px', padding: '1px 8px', fontSize: '11px', fontWeight: 700 }\n","// Taken from shiftPairing rather than timeclock — timeclock re-exports these two from exactly here, but it also pulls\n// in the Supabase client, which needs Vite's env and cannot be loaded by node. Importing it made this whole module\n// untestable, so the payroll maths had no test at all while a copy of it would have drifted silently. Fourth module\n// to take this route, for the same reason as peopleNames, orgDay and shiftPairing itself.\nimport { pairShifts, windowedMs } from './shiftPairing.js'\nimport { localDayStartMs, localDayEndMs } from './format.js'\n\n// Payroll = system of record + export (not in-app tax/filing). This computes per-person hours + PTO for a pay period\n// — the seam a real payroll engine (Gusto/Check) would consume later; HoursExport turns the rows into the CSV/Excel\n// file. Cadence is org-configurable (organizations.pay_period). See design-user-management.md.\n\nconst ONE_DAY = 86400000\nconst REF_SUNDAY_UTC = Date.UTC(2024, 0, 7) // a Sunday — stable anchor for weekly/biweekly boundaries\nconst localMidnight = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate())\nconst fromUTCDay = (utcMs) => { const d = new Date(utcMs); return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) }\n\n// The pay-period window (start inclusive, end exclusive) containing `anchor`, for the given cadence.\nexport function payPeriod(cadence, anchor) {\n const day = localMidnight(anchor)\n if (cadence === 'semimonthly') {\n const y = day.getFullYear(), m = day.getMonth()\n return day.getDate() <= 15\n ? { start: new Date(y, m, 1), end: new Date(y, m, 16) }\n : { start: new Date(y, m, 16), end: new Date(y, m + 1, 1) }\n }\n const len = cadence === 'biweekly' ? 14 : 7\n const dayUTC = Date.UTC(day.getFullYear(), day.getMonth(), day.getDate())\n const idx = Math.floor((dayUTC - REF_SUNDAY_UTC) / (len * ONE_DAY))\n const start = fromUTCDay(REF_SUNDAY_UTC + idx * len * ONE_DAY)\n return { start, end: fromUTCDay(REF_SUNDAY_UTC + (idx + 1) * len * ONE_DAY) }\n}\n\nexport function shiftPeriod(cadence, period, dir) {\n return dir < 0 ? payPeriod(cadence, new Date(period.start.getTime() - ONE_DAY))\n : payPeriod(cadence, period.end)\n}\n\nexport function periodLabel(period) {\n const opt = { month: 'short', day: 'numeric' }\n const last = new Date(period.end.getTime() - ONE_DAY)\n return `${period.start.toLocaleDateString('en-US', opt)} – ${last.toLocaleDateString('en-US', { ...opt, year: 'numeric' })}`\n}\n\n// PTO credited to ONE period. Two bugs lived here: Date.parse('YYYY-MM-DD') is UTC midnight — the previous local\n// evening in Central — so a PTO starting on a period's first day also overlapped the PRIOR period; and the full\n// p.hours went to every overlapping period, paying a boundary-spanning PTO twice. Bounds are local midnights (the\n// same rule as every other date filter — see format.js) and the hours prorate across the periods.\n//\n// PRORATED BY WORKDAYS, NOT CALENDAR DAYS (2026-10-26). A week off filed Thursday to the following Wednesday is five\n// working days and 40 hours, but it spans seven calendar days — so a calendar split put 4/7 of it (22.86h) in the\n// first period, which holds only two of the working days (16h), and paid the weekend as if it were worked. There is\n// no per-org working-days setting, so a workday is Monday to Friday, which is what PTO hours are filed against.\n// A request that holds NO weekday at all (a Saturday filed on its own — drivers do work Saturdays) falls back to\n// calendar days, so its hours still land somewhere rather than vanishing.\n//\n// Days are walked as LOCAL dates through the Date constructor (y, m, d + i), which is immune to DST's 23/25-hour\n// days by construction. The walk is capped so a mistyped end year cannot hang the screen.\nconst MAX_PTO_DAYS = 3700\nexport const isWorkday = (d) => { const w = d.getDay(); return w >= 1 && w <= 5 }\nexport function ptoHoursInPeriod(p, startMs, endMs) {\n const from = localDayStartMs(p.start_date)\n const to = localDayEndMs(p.end_date) // exclusive next-midnight\n if (from == null || to == null || to <= from) return 0\n if (Math.min(to, endMs) - Math.max(from, startMs) <= 0) return 0\n const [y, m, d] = String(p.start_date).split('-').map(Number)\n let work = 0, workIn = 0, all = 0, allIn = 0\n for (let i = 0; i < MAX_PTO_DAYS; i++) {\n const day = new Date(y, m - 1, d + i)\n const t = day.getTime()\n if (t >= to) break\n const inside = t >= startMs && t < endMs\n all++; if (inside) allIn++\n if (isWorkday(day)) { work++; if (inside) workIn++ }\n }\n const share = work > 0 ? workIn / work : (all > 0 ? allIn / all : 0)\n return Math.round((Number(p.hours) || 0) * share * 100) / 100\n}\n\n// IS THIS ROW (a punch, a PTO request) THIS PERSON'S? Either key, ALWAYS — never \"user_id if they have one, else\n// driver_id\". Somebody with BOTH a login and a driver card punches two ways: as a user from the app, and by PIN at\n// the kiosk, which stores `driver_id` alone. The payroll SCREEN read the driver key only when the user key was absent,\n// so on 2026-10-26 five real people with both had every kiosk punch missing from \"Hours this week\", the CSV it\n// downloads and their PTO accrual — while computePayroll (the export) matched either key and showed them. Two copies\n// of one rule, disagreeing about a paycheck. This is the one copy now; both call it.\n//\n// A row carrying both keys still matches once: it is a filter over rows, so nothing can be counted twice.\nexport const belongsTo = (person, row) =>\n !!person && !!row && (\n (!!person.user_id && row.user_id === person.user_id)\n || (!!person.driver_id && row.driver_id === person.driver_id))\n\n// THE NAME A PAYROLL ARTIFACT CALLS SOMEBODY. Legal name first, the name their colleagues use only as a fallback —\n// \"a payroll company sees 'Christina Webb', not 'Chris'\" (2026-07-22). The payroll SCREEN followed that rule from the\n// day it shipped; the EXPORT, which is the thing that actually leaves the building, read `preferred_name` first and\n// nobody saw it, because the export drops zero-hour rows and Christina had not worked a period since. Five of the\n// seven people on the sheet reached the payroll company under a first name only.\n//\n// It lives here, exported, so the screen and the sheet cannot hold two opinions again. Trimmed separately because a\n// preferred_name of \" \" is truthy, and a blank where a name belongs on a payroll sheet is worse than a fallback\n// that says a record needs fixing. The fallback is the caller's: the sheet says \"(no name)\" so payroll chases it; the\n// screen says \"an employee\", which is a sentence, not a row.\nexport const payrollName = (e, fallback = '(no name)') =>\n (e?.legal_name || '').trim() || (e?.preferred_name || '').trim() || fallback\n\n// One row per person for a pay period: hours actually worked plus approved PTO. This is the ONE implementation —\n// HoursExport renders and exports exactly these rows, so a downloaded sheet can never disagree with the screen.\n// Punches attribute by user_id (staff) OR driver_id (drivers, who have no login at all). `events` must arrive with\n// at least a day of margin around the period and unfiltered: windowedMs pairs first and clips second, which is what\n// keeps a boundary-spanning shift from losing its far side. `names` is the user_id/driver_id → display-name map the\n// Time screen already builds; it names punches that match no employee record.\nexport function computePayroll(employees, events, pto, period, nowMs, names = {}) {\n const startMs = period.start.getTime(), endMs = period.end.getTime()\n const capMs = Math.min(nowMs, endMs)\n\n const row = (name, evs) => {\n const mine = [...evs].sort((a, b) => Date.parse(a.at) - Date.parse(b.at))\n const ms = windowedMs(mine, startMs, endMs, capMs)\n return {\n name,\n // Defaulted HERE rather than only on the employee branch, so the stray-punch rows below cannot arrive without\n // one — an undefined key reaching localeCompare throws and takes the whole payroll sheet with it.\n sortKey: name,\n hours: Math.round((ms / 3600000) * 100) / 100,\n ptoHours: 0,\n // A dangling 'in' before the cap means these hours are still accruing — the export must say so rather than\n // hand payroll a mid-shift number that looks final.\n openShift: pairShifts(mine, capMs).some((s) => s.open && Date.parse(s.in) < capMs),\n }\n }\n\n const rows = employees\n .map((emp) => {\n const mine = events.filter((e) => belongsTo(emp, e))\n // payrollName, not a local pick: this line read `preferred_name` first until 2026-08-19 and put \"Matt\" on the\n // sheet against \"Matthew Langenhorst\" on his tax form. See the helper for why it is shared.\n const r = row(payrollName(emp), mine)\n // SORT KEY, carried on the row so the export and the screen cannot order themselves differently. Payroll\n // companies list people by surname; this app shows them by the name their colleagues use. Falls back to the\n // display name when no surname is recorded, so a half-filled roster still reads sensibly instead of collapsing\n // every blank to the top.\n r.sortKey = (emp.last_name || '').trim() || r.name\n // PTO ATTRIBUTES THE SAME TWO WAYS THE PUNCHES ABOVE DO, and it did not until 2026-08-15. `emp.user_id &&`\n // meant a PIN-only driver could never match a PTO row, which was true right up until pto_requests learned to\n // hold a driver on 08-14. From then on, time off entered for a driver was silently DROPPED from this sheet —\n // the one that goes to the payroll company. Faith entered 16.8 hours for one; none of it would have reached\n // payroll, and a missing number on this sheet is the quietest failure it has.\n r.ptoHours = Math.round(pto\n .filter((p) => p.status === 'approved' && belongsTo(emp, p))\n .reduce((s, p) => s + ptoHoursInPeriod(p, startMs, endMs), 0) * 100) / 100\n return { ...r, terminated: emp.status === 'terminated' }\n })\n // A terminated employee stays on the sheet for any period they actually worked or had PTO in — their last check\n // is exactly when payroll needs them — and drops off only once a period holds nothing of theirs.\n .filter((r) => !r.terminated || r.hours > 0 || r.ptoHours > 0 || r.openShift)\n\n // Punches from someone with NO employee record (deleted record, half-finished onboarding) must still reach\n // payroll — silently missing hours is the worst failure this sheet can have. Suffixed so the row explains itself.\n const covered = new Set()\n for (const emp of employees) {\n if (emp.user_id) covered.add(emp.user_id)\n if (emp.driver_id) covered.add(emp.driver_id)\n }\n const strays = {}\n for (const e of events) {\n const key = e.user_id || e.driver_id\n if (!key || covered.has(key)) continue\n const s = strays[key] = strays[key] || { inWindow: false, evs: [] }\n s.evs.push(e)\n const t = Date.parse(e.at)\n if (t >= startMs && t < endMs) s.inWindow = true\n }\n for (const [key, s] of Object.entries(strays)) {\n if (!s.inWindow) continue // margin-only punches belong to the neighboring period\n rows.push(row(`${names[key] || 'Member'} (no employee record)`, s.evs))\n }\n return rows\n}\n\nexport function downloadCsv(filename, text) {\n const blob = new Blob([text], { type: 'text/csv;charset=utf-8;' })\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url; a.download = filename\n document.body.appendChild(a); a.click(); a.remove()\n URL.revokeObjectURL(url)\n}\n","// CSV CELLS — THE ONE DEFINITION. Three exports had grown their own near-identical `esc`/`cell` helper (the fuel\n// export, the payroll week download, the hours export), each of which quoted correctly for CSV STRUCTURE and none\n// of which did anything about the spreadsheet treating a cell as a FORMULA. Same shape as the photo-bounds\n// duplication: a check copied three times does not announce the day one copy stops matching.\n//\n// STRUCTURE AND EXECUTION ARE TWO DIFFERENT PROBLEMS AND ONLY THE FIRST WAS SOLVED. Quoting a value containing a\n// comma keeps the columns lined up; it does nothing about Excel, LibreOffice and Sheets treating a leading `=`,\n// `+`, `-` or `@` as the start of a formula, INSIDE quotes as well as outside — the CSV reader strips the quotes\n// and hands the rest to the same parser that evaluates typed input.\n//\n// THE TRUST BOUNDARY IS WHAT MAKES THIS WORTH FIXING RATHER THAN NOTING. `vendor` and `notes` on a fuel receipt are\n// typed by whoever holds the driver link — a verify_jwt:false endpoint behind a texted URL — and `vendor` is also\n// written from scan-receipt's reading of an attacker-supplied PHOTO. The person who opens the resulting file is the\n// bookkeeper, on an office machine, in a program that runs what it is given. The attacker and the victim are\n// different people, and the victim is the one with the accounting system open.\nconst FORMULA_LEAD = /^[=+\\-@\\t\\r]/;\n\n// Strip only SPACE and NBSP before testing for a lead — deliberately not `\\s`.\n//\n// `\\t` and `\\r` are THEMSELVES formula leads, so a `\\s`-class trim eats the very character it is meant to catch and\n// quietly un-neutralises a tab-led payload. This was written first as `/^[\\s ]+/` and the per-lead cases in\n// scripts/csv-injection.test.mjs failed on it immediately, which is the whole argument for asserting every lead\n// separately rather than only the `=` everyone thinks of.\nconst LEADING_SPACE = /^[ \\u00a0]+/;\n\n// For values a USER supplied. Neutralises the formula lead, then quotes for structure.\n//\n// PREFIX, DO NOT STRIP. Removing the character would silently corrupt a legitimate note (\"-4 gallons short\" is a\n// real thing to write); a leading apostrophe is the standard spreadsheet \"treat this as text\" marker, it survives\n// the round trip, and it is visible enough that nobody mistakes the cell for something the app invented.\n//\n// TEST THE TRIMMED STRING, PREFIX THE ORIGINAL. Anchoring the lead test at position 0 means one leading space walks\n// the payload straight past it — the same anchoring mistake that let a leading space defeat the data: URL guard in\n// supabase/functions/_shared/photo.ts. Trimming only the TEST keeps the stored value byte-exact.\nexport function csvCell(v) {\n const raw = v == null ? '' : String(v);\n const s = FORMULA_LEAD.test(raw.replace(LEADING_SPACE, '')) ? `'${raw}` : raw;\n return /[\",\\n\\r]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n}\n\n// For values WE generate — a number we formatted, a date, a fixed literal like \"Driver\"/\"Office\".\n//\n// A REAL NUMBER IS LEFT BARE, AND THAT IS THE WHOLE REASON THERE ARE TWO FUNCTIONS. A refund renders as -5.00, and\n// running it through csvCell would emit '-5.00 — text, not a number, which does not sum. The fuel export's header\n// states that the figures paste straight into a spreadsheet and add up; a blanket \"neutralise every cell\" would\n// have quietly destroyed the property the export exists for.\n//\n// BUT IT FAILS SAFE INSTEAD OF TRUSTING THE CALL SITE. The first version simply skipped neutralisation, which put\n// the whole guarantee on a human classifying every column correctly, forever, with nothing checking — and it failed\n// in the dangerous direction, since one `csvNumber(r.vendor)` would ship the hole back with the suite still green.\n// So anything that is not actually a bare number falls through to csvCell. Output is byte-identical for every\n// current caller: -5.00, 10.5, 3.29 and 120345 are numeric and stay bare, while '', 2026-07-26, Driver, Office and\n// NaN take the csvCell path and come back unchanged, having no formula lead and no comma.\nconst NUMERIC = /^-?\\d+(\\.\\d+)?$/;\nexport function csvNumber(v) {\n const s = v == null ? '' : String(v);\n return NUMERIC.test(s) ? s : csvCell(s);\n}\n\n// Join already-escaped cells into a row. Exists so a caller cannot forget that escaping happens per CELL, not per\n// row — the bug that a single `row.map(String).join(',')` reintroduces.\nexport const csvRow = (cells) => cells.join(',');\n","import { useEffect, useMemo, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { listEmployees } from '../../lib/employees'\nimport { getEvents, getPto, getPeopleNames } from '../../lib/timeclock'\nimport { payPeriod, shiftPeriod, periodLabel, computePayroll, downloadCsv } from '../../lib/payroll'\nimport { localDayStartMs, localDayEndMs } from '../../lib/format'\nimport { ymd } from '../../lib/schedules'\nimport { ChevronLeft, ChevronRight, Download } from 'lucide-react'\nimport { csvCell, csvNumber, csvRow } from '../../lib/csv'\nimport { Button, Card } from '../ui'\n\n// HOURS + PTO EXPORT, for whoever runs payroll (Faith). Payroll itself is done by an outside payroll company, so this\n// deliberately does NOT compute pay: no rate, no gross, no tax. Just what the payroll company needs — who worked, how\n// many hours, and how much PTO — for a pay period, downloadable.\n//\n// Because it never touches pay_rate or pay_type, it needs none of the restricted payroll columns (see\n// payroll_access_flag.sql). It is still gated to payroll access, since a list of everyone's hours is not for\n// everybody, but the gate is about the audience rather than about the columns.\n//\n// The rows come from computePayroll, which pairs and clips with the SAME windowedMs the timesheet and the punch\n// editor use, so an exported total can never disagree with what the screen showed.\n\nexport default function HoursExport({ profile }) {\n const [cadence, setCadence] = useState('weekly')\n const [anchor, setAnchor] = useState(() => new Date(Date.now() - 7 * 86400000)) // default to LAST period — payroll runs behind\n const [employees, setEmployees] = useState([])\n const [events, setEvents] = useState([])\n const [pto, setPto] = useState([])\n const [names, setNames] = useState({})\n const [loading, setLoading] = useState(true)\n\n // A RANGE THAT IS NOT A PAY PERIOD. Faith, 2026-08-15: \"Each month I process a report that shows hours for the\n // month. I need to be able to enter a specific date range for payroll hours.\" The pay-period arrows can never\n // answer that — a calendar month is not a whole number of weekly or biweekly periods, so a monthly total had to\n // be assembled by hand out of several exports.\n //\n // Everything downstream already took an arbitrary window: computePayroll clips to `period.start`/`period.end` and\n // periodLabel renders whatever it is handed. So this only has to produce a different {start, end}.\n const [mode, setMode] = useState('period') // 'period' = the payroll cadence, 'range' = whatever she types\n const [fromYmd, setFromYmd] = useState('')\n const [toYmd, setToYmd] = useState('')\n\n // Bounds through localDayStartMs/localDayEndMs, never the bare Date constructor: `new Date('YYYY-MM-DD')` is UTC\n // midnight, i.e. the previous evening in Central, and that is the documented way every date filter in this project\n // has silently included the wrong day. `end` is the EXCLUSIVE next midnight, which is the shape computePayroll wants.\n const customPeriod = useMemo(() => {\n const s = localDayStartMs(fromYmd), e = localDayEndMs(toYmd)\n if (s == null || e == null || e <= s) return null\n return { start: new Date(s), end: new Date(e) }\n }, [fromYmd, toYmd])\n\n // An incomplete or backwards range falls back to the pay period rather than blanking the table — a half-typed date\n // is a normal state of a date input, not an error worth clearing the screen for.\n const cadencePeriod = useMemo(() => payPeriod(cadence, anchor), [cadence, anchor])\n const period = (mode === 'range' && customPeriod) ? customPeriod : cadencePeriod\n const rangeLabel = mode === 'range' ? 'Date range' : 'Pay period'\n\n // Opens on the LAST FULL CALENDAR MONTH, which is the report she actually runs, and for the same reason the pay\n // period opens on the previous one: payroll looks backwards.\n function useDateRange() {\n if (!fromYmd && !toYmd) {\n const n = new Date()\n setFromYmd(ymd(new Date(n.getFullYear(), n.getMonth() - 1, 1)))\n setToYmd(ymd(new Date(n.getFullYear(), n.getMonth(), 0)))\n }\n setMode('range')\n }\n\n useEffect(() => {\n if (!profile?.org_id) return\n supabase.from('organizations').select('pay_period').eq('id', profile.org_id).single()\n .then(({ data }) => { if (data?.pay_period) setCadence(data.pay_period) })\n // The same name source the Time screen uses, so a punch that matches no employee record can still land on the\n // sheet under a recognizable name instead of \"Member\".\n getPeopleNames(profile.org_id).then(setNames)\n }, [profile?.org_id])\n\n // CANCELLED ON CHANGE (2026-10-26). Without it, clicking the period arrows quickly let an older, slower response land\n // AFTER a newer one, and the sheet then showed — and exported, under the newer period's filename — another period's\n // hours. Only the response for the period still on screen may set state.\n useEffect(() => {\n if (!profile?.org_id) return\n let live = true\n setLoading(true)\n // A day of margin either side of the period: a shift can span the period boundary, and computePayroll needs the\n // far-side punch to pair it (it clips the hours back to the period itself). Terminated employees are NOT\n // filtered here — someone let go mid-period still gets a final check.\n const s = period.start, e = period.end\n const fromIso = new Date(s.getFullYear(), s.getMonth(), s.getDate() - 1).toISOString()\n const toIso = new Date(e.getFullYear(), e.getMonth(), e.getDate() + 1).toISOString()\n Promise.all([\n listEmployees(profile.org_id), // canPay not needed: no pay columns are read here\n getEvents({ orgId: profile.org_id, fromIso }),\n getPto(profile.org_id),\n ]).then(([emp, ev, p]) => {\n if (!live) return\n setEmployees(emp.rows || [])\n setEvents((ev || []).filter(x => x.at < toIso))\n setPto(p || [])\n setLoading(false)\n })\n return () => { live = false }\n }, [profile?.org_id, period.start, period.end])\n\n // One row per person: hours actually worked in the window, plus approved PTO credited to it.\n const rows = useMemo(() =>\n computePayroll(employees, events, pto, period, Date.now(), names)\n .filter(r => r.hours > 0 || r.ptoHours > 0 || r.openShift) // nobody wants a payroll sheet padded with zero rows\n // BY SURNAME, which is how payroll companies list people (Faith, 2026-08-15). computePayroll carries the key\n // so this sheet and the screen can never order themselves differently; it falls back to the display name for\n // anyone with no surname recorded yet.\n .sort((a, b) => a.sortKey.localeCompare(b.sortKey) || a.name.localeCompare(b.name))\n , [employees, events, pto, period, names])\n\n // ymd(), not toISOString(): the start is a LOCAL midnight, and toISOString renders that as the previous day in\n // every US timezone -- an August report downloading as hours-2026-07-31.\n const fileBase = `hours-${ymd(period.start)}`\n const HEADERS = ['Employee', 'Hours worked', 'PTO hours', 'Open shift']\n // \"Open shift\" marks a still-running clock at download time — a mid-period sheet must say its number isn't final.\n const asRows = () => rows.map(r => [r.name, r.hours, r.ptoHours, r.openShift ? 'yes' : ''])\n\n function exportCsv() {\n // csvCell rather than a local helper: the local one quoted for structure only, so an employee name beginning\n // `=` or `-` reached the payroll spreadsheet as a formula. Hours are csvNumber — neutralising them would emit\n // '0.00 and break the column totals this sheet exists to produce.\n const body = [\n `${rangeLabel},${csvCell(periodLabel(period))}`, '',\n csvRow(HEADERS.map(csvCell)),\n ...asRows().map(r => csvRow([csvCell(r[0]), csvNumber(r[1]), csvNumber(r[2]), csvCell(r[3])])),\n ].join('\\n')\n // Leading BOM so Excel opens it as UTF-8 rather than mangling any accented name.\n downloadCsv(`${fileBase}.csv`, '' + body)\n }\n\n // Excel gets a real spreadsheet via SpreadsheetML rather than a CSV with a renamed extension: a .xls file that is\n // actually HTML makes modern Excel warn that the format and extension do not match, every single time, which is a\n // poor weekly experience for the one person who has to do this.\n function exportExcel() {\n const esc = s => String(s ?? '').replace(/&/g, '&').replace(//g, '>')\n const cell = (v, type) => `${esc(v)}`\n const row = cells => `${cells}`\n const xml =\n `` +\n `` +\n `` +\n `` +\n row(cell(rangeLabel, 'String') + cell(periodLabel(period), 'String')) +\n row('') +\n row(HEADERS.map(h => cell(h, 'String')).join('')) +\n asRows().map(r => row(cell(r[0], 'String') + cell(r[1], 'Number') + cell(r[2], 'Number') + cell(r[3], 'String'))).join('') +\n `
`\n\n const blob = new Blob([xml], { type: 'application/vnd.ms-excel' })\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url; a.download = `${fileBase}.xls`\n document.body.appendChild(a); a.click(); a.remove()\n URL.revokeObjectURL(url)\n }\n\n const totalHours = rows.reduce((s, r) => s + r.hours, 0)\n const totalPto = rows.reduce((s, r) => s + r.ptoHours, 0)\n\n return (\n \n
\n

Hours for payroll

\n {mode === 'period' ? (\n
\n \n {periodLabel(period)}\n \n
\n ) : (\n // The arrows are GONE rather than disabled in this mode: \"previous\" has no meaning for a range somebody\n // typed, and a dead control is a question every time it is seen.\n
\n setFromYmd(e.target.value)} style={dateInp} aria-label=\"From date\" />\n to\n setToYmd(e.target.value)} style={dateInp} aria-label=\"To date\" />\n
\n )}\n
\n\n {/* Which window the sheet covers. Named as what each one is FOR rather than \"custom\": the pay period is what\n the payroll company is paid on, the date range is the monthly report Faith compiles herself. */}\n
\n \n \n {mode === 'range' && !customPeriod && (\n \n Pick a start and an end date — showing the pay period until you do.\n \n )}\n
\n\n {loading ? (\n
Loading…
\n ) : rows.length === 0 ? (\n
\n {mode === 'range'\n ? 'No hours recorded in these dates. Try a different range.'\n : 'No hours recorded in this pay period yet. Use the arrows above to pick another one.'}\n
\n ) : (\n <>\n
\n \n \n \n \n \n \n \n \n \n {rows.map(r => (\n \n \n \n \n \n ))}\n \n \n \n \n \n \n
EmployeeHours workedPTO hours
{r.name}{r.hours}{r.ptoHours || ''}
Total{Math.round(totalHours * 100) / 100}{Math.round(totalPto * 100) / 100 || ''}
\n
\n \n )}\n\n {/* ALWAYS RENDERED, disabled when there is nothing to export. These used to live inside the has-rows branch, so\n on an empty pay period the download controls vanished entirely — you cannot discover a feature that only\n appears once you already have data, and the first person to open this screen sees an empty week. */}\n
\n \n \n Hours and PTO only — pay is calculated by your payroll company.\n
\n
\n )\n}\n\nconst navBtn = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '4px 10px', color: 'var(--text)', fontSize: '16px', cursor: 'pointer', display: 'inline-flex', alignItems: 'center' }\n// 16px on the date inputs deliberately: anything smaller makes iOS Safari zoom the whole page on focus, and this\n// screen is read on a laptop but occasionally checked on a phone.\nconst dateInp = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '5px 8px', color: 'var(--text)', fontSize: '16px', outline: 'none' }\nconst tabBase = { borderRadius: '7px', padding: '5px 12px', fontSize: '14px', fontWeight: 700, cursor: 'pointer' }\n// The selected one is filled rather than merely larger — the same rule the driver controls follow, and it survives\n// being read at a glance by someone who is mid-task.\nconst tabOn = { ...tabBase, background: 'var(--accent)', border: '1px solid var(--accent)', color: '#0b1220' }\nconst tabOff = { ...tabBase, background: 'transparent', border: '1px solid var(--border)', color: 'var(--text-2)' }\nconst th = { color: 'var(--text-2)', fontSize: '13px', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.03em', textAlign: 'right', padding: '4px 8px' }\nconst td = { color: 'var(--text)', fontSize: '15px', padding: '6px 8px', textAlign: 'right', borderBottom: '1px solid var(--border)' }\n","import { sundayOf } from './scheduleDays.js'\nimport { ptoHoursInPeriod } from './payroll.js'\n\n// The PURE half of PTO accrual. It lives apart from pto.js for one reason: pto.js imports ./supabase, so `node`\n// cannot load it, so none of this arithmetic could ever be tested — and it was wrong for seven weeks in production\n// without anything noticing. Same split as schedules.js / scheduleDays.js, for the same reason.\n// scripts/pto-accrual.test.mjs imports THIS file.\n\n// Years of service, or null when the start date is unknown — never guessed.\nexport function yearsOfService(startDate, now = new Date()) {\n if (!startDate) return null\n const ms = now - new Date(startDate + 'T00:00:00')\n return ms <= 0 ? 0 : ms / (365.25 * 24 * 3600 * 1000)\n}\n\n// What ONE full-time week is worth for this person, given the org settings, on the day `at` (a past PTO year is\n// valued at its own tier, not today's). Unknown start date falls to the base tier, as the server does.\nexport function weeklyCreditFor(employee, org, at = new Date()) {\n const yrs = yearsOfService(employee?.start_date, at)\n const threshold = Number(org?.pto_tenure_years ?? 2)\n const tenure = yrs != null && yrs >= threshold\n return {\n tier: tenure ? 'tenure' : 'base',\n hours: Number((tenure ? org?.pto_ft_weekly_hours_2yr : org?.pto_ft_weekly_hours) || 0),\n years: yrs,\n }\n}\n\nconst DAY_MS = 24 * 3600 * 1000\nconst localDate = (ymd) => new Date(ymd + 'T00:00:00')\n\n// WHERE THIS PERSON'S PTO HISTORY BEGINS IN ROUTE NOW — the latest of the start date and the day the carried-in\n// balance was taken.\n//\n// `pto_accrued_hours` is a balance carried in from whatever system came before, hand-entered on some particular day,\n// and it already contains everything earned (and taken) up to that day. Counting from any earlier date credits the\n// overlap TWICE: on org 703 every balance was entered on 2026-07-21, and counting from January 1 credited one\n// long-standing full-timer 73 extra hours against a real balance of 66.\n//\n// `pto_balance_as_of` NULL means nothing was carried in. History then begins at the start date, but never before\n// January 1 of the year the company joined Route Now (or of this year, if that is unknown): before then nothing was\n// tracked here, and replaying a 2019 hire's weeks from 2019 would invent years of accrual nobody recorded.\nexport function ptoHistoryStart(employee, org, now = new Date()) {\n const c = []\n if (employee?.start_date) c.push(localDate(employee.start_date))\n if (employee?.pto_balance_as_of) c.push(localDate(employee.pto_balance_as_of))\n else c.push(new Date((org?.created_at ? new Date(org.created_at) : now).getFullYear(), 0, 1))\n return new Date(Math.max(...c.map((d) => d.getTime())))\n}\n\n// THE PTO YEAR ENDS ON EACH PERSON'S HIRE ANNIVERSARY, NOT DECEMBER 31 (Brian, 2026-10-28: \"It's their anniversary\n// year end.\"). The anniversaries after `from`, up to and including `now`. No start date, no anniversary: nothing ever\n// lapses on a date that was never entered. A Feb 29 hire's anniversary is Mar 1 in other years (what Date does).\nfunction yearEndsBetween(startDate, from, now) {\n if (!startDate) return []\n const s = localDate(startDate)\n const out = []\n for (let y = from.getFullYear(); y <= now.getFullYear(); y++) {\n const a = new Date(y, s.getMonth(), s.getDate())\n if (a > s && a > from && a <= now) out.push(a)\n }\n return out\n}\n\n// The next anniversary after `now`, or null with no start date.\nexport function nextYearEnd(employee, now = new Date()) {\n if (!employee?.start_date) return null\n const s = localDate(employee.start_date)\n for (let y = now.getFullYear(); ; y++) {\n const a = new Date(y, s.getMonth(), s.getDate())\n if (a > now && a > s) return a\n }\n}\n\n// The first day of the CURRENT PTO year: the last anniversary passed, or where the history begins if none has.\nexport function accrualStart(employee, now = new Date(), org) {\n const begin = ptoHistoryStart(employee, org, now)\n const ends = yearEndsBetween(employee?.start_date, begin, now)\n return ends.length ? ends[ends.length - 1] : begin\n}\n\n// Whole weeks since the history began. Full weeks only: crediting a partial first week would pay someone who started\n// on a Friday for that whole week. Both ends are taken to their Sunday so a week is a week regardless of which\n// weekday the anchor happens to be. Counted CUMULATIVELY from the history start, so splitting it at an anniversary\n// (weeksTo(b) - weeksTo(a)) never loses or doubles the week the anniversary falls in.\n//\n// ⚠ DAYLIGHT SAVING, AND IT COSTS A WHOLE WEEK. Two local midnights either side of a DST change are NOT a whole\n// number of 24-hour days apart — a span crossing March in Central time is one hour SHORT, so dividing raw\n// milliseconds gives 35.994 weeks and Math.floor makes that 35. A week of somebody's PTO, silently, and only for\n// part of the year. Caught by CI, which runs in UTC and got 36 where this machine got 35; the divide was wrong on\n// both, and agreed with itself often enough to look right.\n//\n// So: round to whole DAYS first — that absorbs the ±1 hour and nothing else, because two midnights can never be\n// closer than 23 hours — and only then divide into weeks.\nfunction weeksTo(begin, t) {\n if (t <= begin) return 0\n return Math.floor(Math.round((sundayOf(t) - sundayOf(begin)) / DAY_MS) / 7)\n}\n\n// Whole weeks accrued in the current PTO year.\nexport function weeksAccruing(employee, now = new Date(), org) {\n const begin = ptoHistoryStart(employee, org, now)\n return weeksTo(begin, now) - weeksTo(begin, accrualStart(employee, now, org))\n}\n\n// Approved PTO hours falling in [fromMs, toMs). Approved 'pto' only (sick and unpaid never draw on the balance). A\n// request straddling a boundary counts only its workdays on each side, through the same ptoHoursInPeriod the payroll\n// sheet uses, so the balance and the sheet split a boundary week the same way. `requests` must already be THIS\n// person's (payroll.js belongsTo) — matching is the caller's, because callers hold different shapes of person.\nfunction usedBetween(requests, fromMs, toMs) {\n const total = (requests || [])\n .filter((r) => r && r.status === 'approved' && r.kind === 'pto' && r.start_date)\n .reduce((s, r) => s + ptoHoursInPeriod({ ...r, end_date: r.end_date || r.start_date }, fromMs, toMs), 0)\n return Math.round(total * 100) / 100\n}\n\n// PTO USED IN THE CURRENT PTO YEAR, never anything before the carried-in balance was taken: that time off is already\n// out of the balance, and subtracting it again is the spending-side twin of the 73-hour double credit. Approved time\n// off booked ahead counts against this year's balance.\nexport function ptoUsed(requests, employee, now = new Date(), org) {\n return usedBetween(requests, accrualStart(employee, now, org).getTime(), Infinity)\n}\n\n// The most unused hours that cross a year end, or null for no limit (organizations.pto_carryover_max_hours).\nexport function carryoverCap(org) {\n const v = org?.pto_carryover_max_hours\n return v == null || v === '' || !Number.isFinite(Number(v)) ? null : Number(v)\n}\n\n// A PERSON'S PTO BALANCE, YEAR BY YEAR.\n//\n// Starting from the carried-in balance on the day the history begins, walk each hire anniversary up to today. At each\n// one, what was left (opening + earned - used in that year) carries into the next year up to the org's limit, and\n// anything over it is lost (Brian, 2026-10-28: \"they can roll over up to 80 hours of PTO. Anything over 80 is lost.\").\n// Then this year: the carried-over hours plus what has been earned since the last anniversary, less what is used.\n//\n// Earned: full-time is whole weeks x the weekly amount for that year's tier; part-time is hours worked x their hourly\n// rate. `workedHours(fromMs, toMs)` is the caller's, because the caller holds the punches, and it must cover the\n// whole history: callers fetch punches and requests from ptoHistoryStart(), not from January 1.\n//\n// Returns this PTO year's figures (carryover, earned, used, accrued, remaining), when the year began and ends, and\n// what the last year end cost (`lost`, 0 if nothing).\nexport function ptoBalance(employee, { org, requests = [], workedHours = () => 0, now = new Date() } = {}) {\n const cap = carryoverCap(org)\n const begin = ptoHistoryStart(employee, org, now)\n const isFullTime = employee?.employee_type === 'full_time'\n const byType = org?.pto_accrual_by_type || {}\n const rate = employee?.employee_type && byType[employee.employee_type] != null\n ? Number(byType[employee.employee_type])\n : Number(org?.pto_accrual_rate || 0)\n const earnedIn = (from, to, at) => isFullTime\n ? (weeksTo(begin, to) - weeksTo(begin, from)) * weeklyCreditFor(employee, org, at).hours\n : (Number(workedHours(from.getTime(), to.getTime())) || 0) * rate\n\n let opening = Number(employee?.pto_accrued_hours || 0)\n let from = begin\n let lost = 0\n let lastYearEnd = null\n for (const end of yearEndsBetween(employee?.start_date, begin, now)) {\n // Valued at the tier held during that year: the day before it closed.\n const left = opening + earnedIn(from, end, new Date(end.getTime() - DAY_MS)) - usedBetween(requests, from.getTime(), end.getTime())\n const carried = cap != null && left > cap ? cap : left\n lost = left - carried\n lastYearEnd = end\n opening = carried\n from = end\n }\n const earned = now > from ? earnedIn(from, now, now) : 0\n const used = usedBetween(requests, from.getTime(), Infinity)\n const accrued = opening + earned\n return {\n carryover: opening, earned, used, accrued, remaining: accrued - used,\n yearStart: from, yearEnd: nextYearEnd(employee, now), cap, lost, lastYearEnd,\n }\n}\n\n// One line for any PTO card: when this person's PTO year ends and what crosses it. Empty when there is no start date\n// (no anniversary, nothing lapses). Shared so the kiosk card, /me and payroll all say the same thing.\nexport function yearEndNote(bal) {\n if (!bal?.yearEnd) return ''\n const day = bal.yearEnd.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })\n const r = (n) => Math.round((Number(n) || 0) * 100) / 100\n const rule = bal.cap == null ? 'unused hours carry over' : `up to ${r(bal.cap)}h carries over, anything above that is lost`\n const last = bal.lost > 0 && bal.lastYearEnd\n ? ` ${r(bal.lost)}h over the limit was lost on ${bal.lastYearEnd.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}.`\n : ''\n return `PTO year ends ${day}: ${rule}.${last}`\n}\n","import { supabase } from './supabase'\nimport { logAdminAction } from './adminAudit'\nimport { ymd } from './schedules'\n\n// PTO accrual. TWO models (Faith, 2026-07-21), both of them CALCULATIONS — nobody approves PTO week by week.\n//\n// PART-TIME — earned per HOUR WORKED, no tenure tier.\n// FULL-TIME — a flat number of hours per WEEK, tiered by length of service.\n//\n// PTO is meant to be invisible. Faith enters the rates and each person's starting balance once; after that it runs\n// itself, and she only touches it again when someone books time off (pto_requests). An earlier cut of this file made\n// full-time accrual depend on a weekly approval — that was a misreading. The weekly checkbox is a PAYROLL sign-off:\n// \"these hours went to the payroll company and I am not adjusting them again.\" It has nothing to do with PTO, and\n// lives in payrollSignoff below.\n\n// Has this week's payroll been sent? One row per org per week.\nexport async function getWeekSignoff(orgId, weekStart) {\n const { data } = await supabase.from('payroll_week_signoff')\n .select('week_start, sent_name, sent_at, note')\n .eq('org_id', orgId).eq('week_start', typeof weekStart === 'string' ? weekStart : ymd(weekStart))\n .maybeSingle()\n return data || null\n}\n\nexport async function setWeekSent(weekStart, sent, note = null) {\n const { error } = await supabase.rpc('set_payroll_week_sent', {\n p_week_start: typeof weekStart === 'string' ? weekStart : ymd(weekStart),\n p_sent: !!sent,\n p_note: note,\n })\n return { ok: !error, error: error?.message }\n}\n\n// Org-level accrual settings. Left at 0 by the migration on purpose: a guessed default credits real PTO to real\n// people, so nothing accrues until these are filled in deliberately.\nexport async function savePtoSettings(orgId, { ptoByType, ptoDefault, ftWeekly, ftWeekly2yr, tenureYears, carryoverMax }) {\n const patch = {}\n if (ptoByType !== undefined) patch.pto_accrual_by_type = ptoByType\n if (ptoDefault !== undefined) patch.pto_accrual_rate = ptoDefault\n if (ftWeekly !== undefined) patch.pto_ft_weekly_hours = ftWeekly\n if (ftWeekly2yr !== undefined) patch.pto_ft_weekly_hours_2yr = ftWeekly2yr\n if (tenureYears !== undefined) patch.pto_tenure_years = tenureYears\n // null = no limit (everything carries over at the anniversary year end); see pto_carryover_max_hours.sql.\n if (carryoverMax !== undefined) patch.pto_carryover_max_hours = carryoverMax\n const { error } = await supabase.from('organizations').update(patch).eq('id', orgId)\n if (!error) {\n logAdminAction('pto.settings', 'updated the PTO accrual settings', {\n targetTable: 'organizations', targetId: orgId, detail: { changes: patch },\n })\n }\n return { ok: !error, error: error?.message }\n}\n\n// The balance people are carrying in from whatever system they came from. This is the ONLY hand-entered number in the\n// accrual, so it is audited by name rather than folded into a bulk employee save.\n//\n// IT NOW STAMPS THE DAY IT WAS TAKEN, and that date is load-bearing rather than decorative: accrual runs FROM it.\n// Without it the balance floats free of any date and the calculation falls back to January 1, crediting the months\n// the balance already covers a second time — which is exactly what happened to org 703 between 2026-07-21 and\n// 2026-09-09. Local date, never toISOString(): after 7pm Central the UTC day is tomorrow, and a balance stamped a\n// day into the future silently loses a week of accrual.\nexport async function setStartingBalance(employeeId, hours, { person, asOf } = {}) {\n const v = hours === '' || hours == null ? 0 : Number(hours)\n if (!Number.isFinite(v) || v < 0) return { ok: false, error: 'Enter a number of hours, 0 or more.' }\n const d = asOf || ymd(new Date())\n const { error } = await supabase.from('employees')\n .update({ pto_accrued_hours: v, pto_balance_as_of: d }).eq('id', employeeId)\n if (error) return { ok: false, error: error.message }\n logAdminAction('pto.starting_balance', `set ${person || 'an employee'}'s starting PTO balance to ${v} hours as of ${d}`, {\n targetId: employeeId, targetTable: 'employees', targetLabel: person || null,\n detail: { pto_accrued_hours: v, pto_balance_as_of: d },\n })\n return { ok: true }\n}\n\n// The accrual ARITHMETIC now lives in ./ptoMath, which imports nothing from Supabase and can therefore be loaded by\n// `node` and tested — scripts/pto-accrual.test.mjs does. It was in this file until 2026-09-09, unreachable by any\n// test because of the supabase import at the top, and it was wrong in production for seven weeks. Re-exported here\n// so no call site had to move.\nexport { yearsOfService, weeklyCreditFor, accrualStart, weeksAccruing, ptoUsed, ptoBalance, ptoHistoryStart, nextYearEnd, carryoverCap, yearEndNote } from './ptoMath'\n","import { useEffect, useMemo, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { getSchedule, sundayOf, ymd, addDays, SCHED_DAYS, DAY_LABEL, fmtHhmm, dayHours, defaultDays } from '../../lib/schedules'\nimport { clockState, getEvents, pairShifts, getPto, addPto, deletePto } from '../../lib/timeclock'\nimport { ptoBalance, ptoHistoryStart, yearEndNote } from '../../lib/pto'\nimport { ChevronLeft, ChevronRight, Trash2 } from 'lucide-react'\nimport ClockConfirmModal from '../Time/ClockConfirmModal'\nimport BirthdayCelebration from '../Birthday/BirthdayCelebration'\nimport { Button, Card } from '../ui'\n\n// The logged-in driver's self-service portal (role = 'driver'). Blocks, top to bottom: clock in/out, this week's\n// schedule, timesheet, time-off requests, and accrued PTO. Self-contained (own minimal header) so drivers never touch\n// the admin nav. Delivery routes still live on the token/`/d` driver page.\nexport default function DriverPortal({ profile }) {\n const [refresh, setRefresh] = useState(0) // bump to reload the timesheet after a punch\n return (\n
\n {/* The org name truncates rather than shoving Log out off the edge. This portal has no hamburger and no other\n way to sign out, so on a phone any org with a normal-length legal name could strand the only exit. */}\n
\n {profile?.organizations?.name || 'Route Now'}\n \n
\n
\n

Hi{profile?.full_name ? `, ${profile.full_name.split(' ')[0]}` : ''} 👋

\n setRefresh((n) => n + 1)} />\n \n \n \n \n
\n \n
\n )\n}\n\n// 1) Clock in / out\nfunction ClockCard({ profile, onPunched }) {\n const [st, setSt] = useState(null)\n const [pending, setPending] = useState(null)\n useEffect(() => { clockState().then((r) => setSt(r?.error ? { clockedIn: false } : r)) }, [])\n function onDone(r) {\n if (r?.error) window.alert(r.error); else { setSt(r); onPunched?.() }\n setPending(null)\n }\n const inNow = !!st?.clockedIn\n return (\n \n
\n
{inNow ? 'Clocked in' : 'Not clocked in'}
\n {inNow && st?.since &&
since {clockAt(st.since)}
}\n
\n \n {pending && setPending(null)} onDone={onDone} />}\n
\n )\n}\n\n// 2) This week's schedule\nfunction MySchedule({ profile }) {\n const [days, setDays] = useState(null)\n const [ready, setReady] = useState(false)\n const weekStart = sundayOf()\n useEffect(() => {\n // PROFILE IS NULL UNTIL ITS ROW ARRIVES, AND THIS RENDERS BEFORE IT DOES. App.jsx routes /me and /time on the\n // SESSION alone (profile starts as useState(null)), so every component here renders once with profile === null.\n // A dependency array is evaluated during that render, so `profile.id` in one threw \"Cannot read properties of\n // null (reading 'org_id')\" and took the whole page down to its error boundary -- on /me, the driver's own\n // portal, as well as /time. Only on a COLD load: a refresh, a bookmark, a typed URL, or a home_path landing.\n // Arriving from another screen never hit it, because the profile was already there by then, which is how a\n // crash on two landing pages went unseen. Guarded here AND optional-chained in the deps, so each card holds its\n // own loading state until the profile lands and the effect re-runs with it.\n if (!profile?.id || !profile?.org_id) return\n let cancelled = false\n async function load() {\n const { data: emp } = await supabase.from('employees').select('driver_id').eq('user_id', profile.id).maybeSingle()\n const driverId = emp?.driver_id\n if (!driverId) { if (!cancelled) { setDays(null); setReady(true) } return }\n let d = await getSchedule(profile.org_id, driverId, ymd(weekStart))\n if (!d) {\n const { data: dr } = await supabase.from('drivers').select('default_schedule').eq('id', driverId).maybeSingle()\n d = dr?.default_schedule || defaultDays()\n }\n if (!cancelled) { setDays(d); setReady(true) }\n }\n load()\n return () => { cancelled = true }\n }, [profile?.id, profile?.org_id]) // eslint-disable-line react-hooks/exhaustive-deps\n const total = days ? SCHED_DAYS.reduce((s, k) => s + dayHours(days[k]), 0) : 0\n const range = `${weekStart.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – ${addDays(weekStart, 6).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`\n return (\n \n

My schedule

{range}
\n {!ready ?
Loading…
: !days ?
No schedule assigned yet — your manager will set it.
: (\n <>\n {SCHED_DAYS.map((k) => {\n const d = days[k] || {}; const off = d.off || !d.start || !d.end\n return (\n
\n {DAY_LABEL[k]}\n {off ? 'Off' : `${fmtHhmm(d.start)}–${fmtHhmm(d.end)}`}\n
\n )\n })}\n
Scheduled hours{round(total)}h
\n \n )}\n
\n )\n}\n\n// 3) Timesheet — clocked hours by day, week-navigable\nfunction Timesheet({ profile, refresh }) {\n const [weekStart, setWeekStart] = useState(() => sundayOf())\n const [events, setEvents] = useState([])\n const fromIso = useMemo(() => new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate()).toISOString(), [weekStart])\n const toIso = useMemo(() => addDays(weekStart, 7).toISOString(), [weekStart])\n useEffect(() => {\n if (!profile?.id) return // null until the profile row arrives -- see the schedule card above\n getEvents({ userId: profile.id, fromIso }).then((ev) => setEvents((ev || []).filter((e) => e.at < toIso)))\n }, [profile?.id, fromIso, toIso, refresh])\n const shifts = useMemo(() => pairShifts(events, Date.now()), [events])\n const byDay = useMemo(() => { const g = {}; for (const s of shifts) { const d = ymd(new Date(s.in)); (g[d] = g[d] || []).push(s) } return g }, [shifts])\n const weekMs = shifts.reduce((s, x) => s + x.ms, 0)\n const range = `${weekStart.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – ${addDays(weekStart, 6).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`\n return (\n \n
\n

Timesheet

\n
\n \n {range}\n \n
\n
\n {Object.keys(byDay).length === 0 ?
No punches this week.
: Object.entries(byDay).map(([d, list]) => (\n
\n {dayName(d)}\n \n {list.map((s, i) => {clockAt(s.in)}–{s.out ? clockAt(s.out) : 'now'}{i < list.length - 1 ? ', ' : ''})}\n {round(list.reduce((a, s) => a + s.ms, 0) / 3600000)}h\n \n
\n ))}\n
Total{round(weekMs / 3600000)}h
\n
\n )\n}\n\n// 4) Time off — request + see own requests\nfunction TimeOff({ profile }) {\n const [pto, setPto] = useState([])\n const [form, setForm] = useState({ start_date: ymd(new Date()), end_date: ymd(new Date()), kind: 'pto', hours: '', note: '' })\n const load = () => getPto(profile.org_id).then((rows) => setPto((rows || []).filter((r) => r.user_id === profile.id)))\n // Guarded rather than called blind -- see the schedule card above. `load` is also called after a submit, by\n // which point the profile is certainly there.\n useEffect(() => { if (profile?.org_id && profile?.id) load() }, [profile?.org_id, profile?.id]) // eslint-disable-line react-hooks/exhaustive-deps\n async function submit(e) {\n e.preventDefault()\n // A driver requesting their OWN time off — this portal is reached with a login, so the subject is the user id.\n const r = await addPto(profile.org_id, { userId: profile.id }, { ...form, hours: form.hours ? Number(form.hours) : null })\n if (r.ok) { setForm({ start_date: ymd(new Date()), end_date: ymd(new Date()), kind: 'pto', hours: '', note: '' }); load() } else window.alert(r.error)\n }\n const statusColor = { pending: '#f59e0b', approved: 'var(--accent)', denied: '#ef4444' }\n return (\n \n

Time off

\n \n \n \n \n \n \n \n {pto.length === 0 ?
No requests yet.
: pto.map((r) => (\n
\n {r.start_date}{r.end_date !== r.start_date ? `–${r.end_date}` : ''} · {r.kind}{r.hours ? ` · ${r.hours}h` : ''}\n \n {r.status}\n {r.status === 'pending' && }\n \n
\n ))}\n
\n )\n}\n\n// 5) Accrued PTO. Reads lib/pto ptoBalance — the SAME calculation the payroll screen uses — so a full-timer's own\n// portal never disagrees with what Faith sees. The PTO year runs anniversary to anniversary. Full-time = whole weeks\n// × the weekly amount for their tier; part-time = hours worked × their hourly rate. Both + carryover, minus PTO used.\nexport function AccruedPto({ profile }) {\n const org = profile?.organizations || {}\n const [emp, setEmp] = useState(null) // { employee_type, start_date, pto_accrued_hours }\n const [events, setEvents] = useState([])\n const [ptoRows, setPtoRows] = useState([])\n const [loaded, setLoaded] = useState(false)\n useEffect(() => {\n // See the schedule card above. This card is the one the TIME screen renders, so a null profile took /time down\n // even though nothing else on that screen touched it.\n if (!profile?.id || !profile?.org_id) return\n // start_date is load-bearing twice: it decides the full-time tenure tier AND the PTO year end (the anniversary).\n // Punches are fetched from where the PTO history begins (ptoHistoryStart), not January 1, because a year end\n // that has already passed needs the hours worked in the year it closed.\n supabase.from('employees').select('pto_accrued_hours, pto_balance_as_of, employee_type, start_date').eq('user_id', profile.id).maybeSingle().then(({ data }) => {\n const e = data || {}\n setEmp(e)\n getEvents({ userId: profile.id, fromIso: ptoHistoryStart(e, org).toISOString() }).then((ev) => { setEvents(ev || []); setLoaded(true) })\n })\n // Raw rows, not a pre-summed number: which year a day off belongs to depends on the anniversary, which needs `emp`.\n supabase.from('pto_requests').select('hours, kind, status, start_date, end_date').eq('org_id', profile.org_id).eq('user_id', profile.id)\n .then(({ data }) => setPtoRows(data || []))\n }, [profile?.org_id, profile?.id]) // eslint-disable-line react-hooks/exhaustive-deps\n // Hours worked in a window. Whole shifts, by start: a shift straddling a boundary belongs to the side it began on,\n // and at one shift's granularity that is not worth clipping for.\n const shifts = useMemo(() => pairShifts(events, Date.now()), [events])\n const workedHours = (fromMs, toMs) => shifts.filter((s) => { const t = Date.parse(s.in); return t >= fromMs && t < toMs }).reduce((sum, s) => sum + s.ms, 0) / 3600000\n const isFullTime = emp?.employee_type === 'full_time'\n const rate = emp?.employee_type && (org.pto_accrual_by_type || {})[emp.employee_type] != null\n ? Number((org.pto_accrual_by_type)[emp.employee_type]) : Number(org.pto_accrual_rate || 0)\n const bal = loaded ? ptoBalance(emp || {}, { org, requests: ptoRows, workedHours }) : null\n const carryover = bal?.carryover ?? 0\n const earned = bal?.earned ?? 0\n const used = bal?.used ?? 0\n const accrued = bal?.accrued ?? null\n const remaining = bal?.remaining ?? null\n const workedYtd = bal ? workedHours(bal.yearStart.getTime(), Infinity) : 0\n const stat = (label, val, color) => (\n
\n
{val}
\n
{label}
\n
\n )\n return (\n \n

Accrued PTO

\n {!loaded ?
Loading…
: (\n <>\n
\n {stat('Accrued', `${round(accrued)}h`)}\n {stat('Used', `${round(used)}h`, 'var(--text-2)')}\n {stat('Remaining', `${round(remaining)}h`, remaining < 0 ? '#ef4444' : '#4ade80')}\n
\n
\n {isFullTime\n ? `Earned ${round(earned)}h this PTO year${carryover ? ` + ${round(carryover)}h carryover` : ''}.`\n : `Earned ${round(earned)}h this PTO year (${round(workedYtd)}h worked × ${rate}/hr)${carryover ? ` + ${round(carryover)}h carryover` : ''}.`}\n {bal?.yearEnd && <> {yearEndNote(bal)}}\n
\n \n )}\n
\n )\n}\n\nconst round = (n) => Math.round((Number(n) || 0) * 100) / 100\nconst clockAt = (iso) => new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n// date-only \"YYYY-MM-DD\" group key — anchor at local noon, not new Date(key) which parses as UTC and renders a day\n// early in US timezones (the \"punches show one day early\" bug). Matches PunchEditor's dayLabel.\nconst dayName = (key) => new Date(key + 'T12:00:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })\n\nconst h2 = { color: 'var(--text)', fontSize: '21px', fontWeight: 800, margin: 0 }\nconst sub = { color: 'var(--text-2)', fontSize: '14px' }\nconst muted = { color: 'var(--text-2)', fontSize: '15px' }\nconst rowBetween = { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '0.75rem' }\nconst lineItem = { display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderBottom: '1px solid var(--border)' }\nconst navBtn = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '4px 10px', color: 'var(--text)', fontSize: '16px', cursor: 'pointer' }\nconst inp = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '7px 9px', color: 'var(--text)', fontSize: '16px', outline: 'none' }\nconst fieldLabel = { display: 'flex', flexDirection: 'column', gap: '3px', color: 'var(--text-2)', fontSize: '14px' }\n","import { useEffect, useMemo, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { sundayOf, addDays, ymd } from '../../lib/schedules'\nimport { getEvents, pairShifts, windowedMs, getPto, addPto, setPtoStatus, deletePto, clockState, getPeopleNames, getPeopleOptions, getWhoIsOn } from '../../lib/timeclock'\nimport PunchEditor from './PunchEditor'\nimport HoursExport from './HoursExport'\nimport { canViewPayroll } from '../../lib/pageAccess'\nimport { SCHED_DAYS, DAY_LABEL, DAY_OFFSET, fmtHhmm, getSchedule, ymd as ymdOf } from '../../lib/schedules'\nimport { ChevronLeft, ChevronRight, X, Trash2 } from 'lucide-react'\nimport ClockConfirmModal from './ClockConfirmModal'\nimport { AccruedPto } from '../Driver/DriverPortal' // same balance card the driver portal shows — office staff had NO PTO balance anywhere\nimport { Button, Card, Input } from '../ui'\n\nconst h2 = { color: 'var(--text)', fontSize: '21px', fontWeight: 800, margin: '0 0 0.75rem' }\nconst inp = { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '7px', padding: '7px 9px', color: 'var(--text)', fontSize: '16px', outline: 'none' }\nconst dayKeyOf = (d) => ({ 1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat' })[d.getDay()] || null\nconst fmtHrs = (ms) => `${Math.round((ms / 3600000) * 100) / 100}h`\n// `key` is a date-only \"YYYY-MM-DD\" (the shiftsByDay group key). new Date(\"2026-07-20\") parses as UTC midnight, which in\n// any US timezone (all behind UTC) renders as the PREVIOUS day — the \"punches all show one day early / starting on\n// Sunday\" bug. Anchor at local noon so the weekday label matches the day the punch actually happened. (PunchEditor's\n// dayLabel already does this; this one and the driver portal's were the two that didn't.)\nconst dayName = (key) => new Date(key + 'T12:00:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })\nconst clock = (iso) => new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n// \"5h 44m\" / \"18m\" / \"2d 4h\" — how long somebody has been on the clock. Deliberately NOT fmtHrs's decimal hours:\n// 5.73h is a figure for a timesheet, and the question this card answers is \"how long have they been here\".\nconst elapsed = (ms) => {\n const mins = Math.max(0, Math.floor(ms / 60000))\n const d = Math.floor(mins / 1440)\n const h = Math.floor((mins % 1440) / 60)\n const m = mins % 60\n if (d) return `${d}d ${h}h`\n if (h) return `${h}h ${m}m`\n return `${m}m`\n}\n// A bare clock time is a lie on a punch that is not from today — \"since 7:58 AM\" reads as this morning whether the\n// punch is four hours old or four days. The weekday appears exactly when it changes the meaning.\nconst sinceLabel = (iso) => {\n const d = new Date(iso)\n const sameDay = d.toDateString() === new Date().toDateString()\n return sameDay ? clock(iso) : `${d.toLocaleDateString('en-US', { weekday: 'short' })} ${clock(iso)}`\n}\n\nexport default function TimeScreen({ profile }) {\n const isAdmin = !!(profile?.is_super_admin || profile?.role === 'admin' || profile?.role === 'owner')\n const [weekStart, setWeekStart] = useState(() => sundayOf())\n const [people, setPeople] = useState({}) // user_id -> name\n const [myEvents, setMyEvents] = useState([])\n const [teamEvents, setTeamEvents] = useState([])\n const [pto, setPto] = useState([])\n const [st, setSt] = useState(null)\n const [pending, setPending] = useState(null) // 'in' | 'out' while the confirm modal is open\n const [form, setForm] = useState({ start_date: ymd(new Date()), end_date: ymd(new Date()), kind: 'pto', hours: '', note: '' })\n // WHO the time off is for. Empty string means \"me\", so the form behaves exactly as it always did for anyone who is\n // not filing on someone else's behalf. Only managers ever see the control — the INSERT policy allows admin, owner\n // and dispatcher to file for another person, and this matches it rather than inventing a second rule.\n const [ptoFor, setPtoFor] = useState('')\n const [peopleList, setPeopleList] = useState([])\n // The signed-in person's own schedule for the week on view. Keyed by the PERSON since 2026-09-05, so an office-only\n // staff member with no driver card now has one to show — which is the half of Sara's problem that lands here: she\n // could not be scheduled, and even once she could, this card was reading through a driver_id she does not have.\n const [myDays, setMyDays] = useState(undefined)\n // Who is punched in right now, and the wall clock the card's elapsed times are measured against. Kept as state\n // rather than read from Date.now() at render, so every row on the card is measured from the SAME instant as the\n // read that produced it — otherwise \"as of 3:42\" sits beside a duration computed at 3:43.\n const [onClock, setOnClock] = useState(null)\n const [nowMs, setNowMs] = useState(() => Date.now())\n const todayKey = dayKeyOf(new Date())\n\n // Fetch a day of margin either side of the week: a shift can SPAN the week boundary, and cutting events to the\n // window before pairing dropped the far-side punch (the lone 'out' paired with nothing). Totals clip back to the\n // week itself via windowedMs.\n const fromIso = useMemo(() => new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate() - 1).toISOString(), [weekStart])\n const toIso = useMemo(() => addDays(weekStart, 8).toISOString(), [weekStart])\n const weekEndMs = useMemo(() => addDays(weekStart, 7).getTime(), [weekStart])\n\n function loadWeek() {\n if (!profile?.org_id) return\n getEvents({ userId: profile.id, fromIso }).then(ev => setMyEvents(ev.filter(e => e.at < toIso)))\n if (isAdmin) getEvents({ orgId: profile.org_id, fromIso }).then(ev => setTeamEvents(ev.filter(e => e.at < toIso)))\n }\n useEffect(loadWeek, [profile?.org_id, profile?.id, fromIso, toIso, isAdmin])\n\n // ON THE CLOCK NOW. Its own read, on its own timer, deliberately independent of the week the timesheet is showing:\n // paging back to check last month's hours must not change who the card says is in the building.\n //\n // It re-reads on a timer because the card's entire claim is the word \"now\" — this screen sits open on a desk all\n // day, and a roster captured when the tab was opened would go on asserting a morning that has ended.\n function refreshOnClock() {\n if (!profile?.org_id || !isAdmin) return\n const now = Date.now()\n setNowMs(now)\n getWhoIsOn(profile.org_id, { now }).then(setOnClock)\n }\n useEffect(() => {\n if (!profile?.org_id || !isAdmin) return\n refreshOnClock()\n const id = setInterval(refreshOnClock, 60000)\n return () => clearInterval(id)\n }, [profile?.org_id, isAdmin]) // eslint-disable-line react-hooks/exhaustive-deps\n useEffect(() => {\n if (!profile?.org_id) return\n // Staff punch as a logged-in user, drivers punch by PIN with no login at all, so both key spaces are resolved --\n // see getPeopleNames, which is also the reason a non-super-admin now sees a name here instead of \"Unknown\".\n getPeopleNames(profile.org_id).then(setPeople)\n if (isAdmin) getPeopleOptions(profile.org_id).then(setPeopleList)\n getPto(profile.org_id).then(setPto)\n clockState().then(r => setSt(r?.error ? { clockedIn: false } : r))\n }, [profile?.org_id, isAdmin])\n\n useEffect(() => {\n let cancelled = false\n if (!profile?.org_id || !profile?.id) return\n supabase.from('employees').select('id, driver_id, on_schedule, default_schedule').eq('user_id', profile.id).is('deleted_at', null).maybeSingle()\n .then(async ({ data: emp }) => {\n if (cancelled) return\n // Somebody ticked OFF the schedule has no week to show, and showing them an inherited 8-4 default would be a\n // claim about hours they are not rostered for.\n if (!emp || emp.on_schedule === false) { setMyDays(null); return }\n const days = await getSchedule(profile.org_id, { id: emp.id, driverId: emp.driver_id }, ymdOf(weekStart))\n if (days) { if (!cancelled) setMyDays(days); return }\n if (!cancelled) setMyDays(emp.default_schedule || null)\n })\n return () => { cancelled = true }\n }, [profile?.org_id, profile?.id, weekStart])\n\n // Cap open shifts at the END of the week on view, never just Date.now(): while browsing a past week the wall\n // clock let a still-open shift bleed everything since that week into its total — and disagree with the payroll\n // export, which caps. Shift ms are clipped to the week so day totals sum to exactly the week header.\n const myShifts = useMemo(() => {\n const weekStartMs = weekStart.getTime()\n const capMs = Math.min(Date.now(), weekEndMs)\n return pairShifts(myEvents, capMs)\n .map(sh => {\n const from = Math.max(Date.parse(sh.in), weekStartMs)\n const to = Math.min(sh.out ? Date.parse(sh.out) : capMs, weekEndMs, capMs)\n return { ...sh, ms: Math.max(0, to - from) }\n })\n .filter(sh => sh.ms > 0)\n }, [myEvents, weekStart, weekEndMs])\n const myWeekMs = myShifts.reduce((s, sh) => s + sh.ms, 0)\n const shiftsByDay = useMemo(() => {\n const g = {}\n // Group under the day the IN-WEEK portion starts: the tail of an overnight shift from the margin day lists\n // under the week's first day instead of conjuring a day row from the previous week.\n for (const sh of myShifts) { const d = ymd(new Date(Math.max(Date.parse(sh.in), weekStart.getTime()))); (g[d] = g[d] || []).push(sh) }\n return g\n }, [myShifts, weekStart])\n\n // Key on user_id OR driver_id. Staff punch as a logged-in user; drivers punch by PIN with no login at all, so\n // their events carry driver_id and a NULL user_id -- keying on user_id alone merged every driver into a single\n // nameless row, which would have been the first thing anyone noticed on day one of the rollout.\n const teamTotals = useMemo(() => {\n const byPerson = {}\n for (const e of teamEvents) {\n const key = e.user_id || e.driver_id\n if (!key) continue\n ;(byPerson[key] = byPerson[key] || []).push(e)\n }\n const capMs = Math.min(Date.now(), weekEndMs)\n return Object.entries(byPerson)\n .map(([uid, ev]) => ({\n uid,\n ms: windowedMs(ev, weekStart.getTime(), weekEndMs, capMs),\n // A capped shift must SAY it is capped. The number beside it is deliberately not what the clock reads, and a\n // total that quietly disagrees with the punches is worse than the runaway it replaced — at least 57 hours was\n // obviously wrong. This is what makes 8 hours obviously provisional.\n needsCorrection: pairShifts(ev, capMs).some(s => s.needsCorrection),\n }))\n .sort((a, b) => b.ms - a.ms)\n }, [teamEvents, weekStart, weekEndMs])\n\n function onPunchDone(r) {\n if (r?.error) window.alert(r.error); else { setSt(r); loadWeek(); refreshOnClock() }\n setPending(null)\n }\n async function submitPto(e) {\n e.preventDefault()\n // Blank picker = filing for myself, which is every case this form handled before today.\n const chosen = ptoFor ? peopleList.find(p => p.id === ptoFor) : null\n const subject = chosen\n ? (chosen.kind === 'driver' ? { driverId: chosen.id } : { userId: chosen.id })\n : { userId: profile.id }\n // FILED BY A MANAGER IS ALREADY DECIDED. Faith is entering time off that was taken, not requesting it — leaving it\n // 'pending' would mean she had to approve her own entry on a second screen to make it count, which is exactly the\n // busywork she asked to be rid of. Somebody filing for THEMSELVES still goes through approval, unchanged.\n const status = chosen ? 'approved' : undefined\n const r = await addPto(profile.org_id, subject, {\n ...form,\n hours: form.hours ? Number(form.hours) : null,\n ...(status ? { status } : {}),\n })\n if (r.ok) {\n setForm({ start_date: ymd(new Date()), end_date: ymd(new Date()), kind: 'pto', hours: '', note: '' })\n setPtoFor('')\n getPto(profile.org_id).then(setPto)\n }\n else window.alert(r.error)\n }\n // Results are READ (2026-10-26). Both threw the answer away, so a refused approve or delete looked like it worked\n // until the list was re-read. The list is re-read either way — that is what puts the row back to its real state —\n // and a failure is said out loud, the same way filing one already was.\n async function decide(id, status) {\n const r = await setPtoStatus(id, status)\n getPto(profile.org_id).then(setPto)\n if (!r.ok) window.alert(`Could not ${status === 'approved' ? 'approve' : status === 'denied' ? 'deny' : 'update'} that request: ${r.error}`)\n }\n async function removePto(id) {\n const r = await deletePto(id)\n getPto(profile.org_id).then(setPto)\n if (!r.ok) window.alert(`Could not delete that request: ${r.error}`)\n }\n\n const fmtRange = (d) => `${weekStart.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – ${addDays(weekStart, 6).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`\n const statusColor = { pending: '#f59e0b', approved: 'var(--accent)', denied: '#ef4444' }\n\n return (\n
\n

Time

\n\n {/* ON THE CLOCK NOW — first on the page, because for the person who can see it this is the reason they opened it.\n It displaces nothing: the clock card below is self-service and is hidden for salaried staff anyway, so for a\n salaried admin this screen used to open on somebody else's timesheet.\n\n Admin-gated to match Team hours. It carries a person's start time and hours-so-far, which is the same class of\n figure, so widening who can read it is a decision rather than a detail.\n\n THE TWO GROUPS ARE NOT THE SAME CLAIM. `on` is a shift genuinely in progress. `stale` is an open punch past\n the 16-hour forgotten threshold — somebody who went home without clocking out — and folding it into the first\n list would put a person on a \"who is here now\" board days after they left, which is exactly the kind of\n confident wrong answer this screen would then be trusted for. */}\n {isAdmin && (\n \n
\n

On the clock now

\n \n {onClock ? `${onClock.on.length} in · as of ${clock(new Date(nowMs).toISOString())}` : 'Loading…'}\n \n
\n\n {onClock && (onClock.on.length === 0\n ?
Nobody is clocked in.
\n : onClock.on.map(p => (\n
\n \n \n {people[p.key] || 'Member'}\n \n \n since {sinceLabel(p.since)}{elapsed(p.elapsedMs)}\n \n
\n )))}\n\n {onClock && onClock.stale.length > 0 && (\n
\n
\n ⚠ Still open — needs a clock-out\n
\n
\n Not counted above. Fix the time in Punch corrections below.\n
\n {onClock.stale.map(p => (\n
\n {people[p.key] || 'Member'}\n in since {sinceLabel(p.since)} · {elapsed(p.elapsedMs)} ago\n
\n ))}\n
\n )}\n
\n )}\n\n {/* Clock card — salaried staff don't punch a clock, so it's hidden for them. */}\n {profile?.pay_type !== 'salary' && (\n \n
\n
{st?.clockedIn ? 'Clocked in' : 'Not clocked in'}
\n
This week: {fmtHrs(myWeekMs)}
\n
\n \n
\n )}\n\n {pending && setPending(null)} onDone={onPunchDone} />}\n\n {/* YOUR WEEK. Sits right under the clock button on purpose: the question someone has at the moment they punch\n is \"am I due in now, and when am I next on?\" -- the timesheet below answers what already happened, which is\n a different question. Only rendered when there IS a schedule; schedules are per driver, so office-only\n staff have none and get nothing rather than an empty grid. */}\n {myDays && (\n \n

Your week · {fmtRange()}

\n {SCHED_DAYS.map(k => {\n const isToday = k === todayKey\n const off = !myDays[k] || myDays[k].off\n return (\n
\n \n {DAY_LABEL[k]} {addDays(weekStart, DAY_OFFSET[k]).getDate()}\n \n \n {off ? 'Off' : `${fmtHhmm(myDays[k].start)}–${fmtHhmm(myDays[k].end)}`}\n \n
\n )\n })}\n
\n )}\n\n {/* My timesheet */}\n \n
\n

My timesheet

\n
\n \n {fmtRange()}\n \n
\n
\n {Object.keys(shiftsByDay).length === 0 ? (\n
No punches this week.
\n ) : Object.entries(shiftsByDay).map(([d, shifts]) => (\n
\n {dayName(d)}\n \n {shifts.map((s, i) => {clock(s.in)}–{s.out ? clock(s.out) : 'now'}{i < shifts.length - 1 ? ', ' : ''})}\n {fmtHrs(shifts.reduce((a, s) => a + s.ms, 0))}\n \n
\n ))}\n
\n\n {/* Hours + PTO for the payroll company. Payroll access only — a sheet of everyone's hours is not for every\n manager — and it is placed above Team hours because for the person who lands here, it is the reason they\n came. Reads no pay columns at all, so the payroll-column restriction does not apply to it. */}\n {canViewPayroll(profile) && }\n\n {/* Team totals (admin) */}\n {isAdmin && teamTotals.length > 0 && (\n \n

Team hours · {fmtRange()}

\n {teamTotals.map(t => (\n
\n \n {people[t.uid] || 'Member'}\n {t.needsCorrection && (\n \n ⚠ no clock-out\n \n )}\n \n {fmtHrs(t.ms)}\n
\n ))}\n
\n )}\n\n {/* Punch corrections (admin) */}\n {isAdmin && (\n { loadWeek(); refreshOnClock() }}\n />\n )}\n\n {/* Accrued PTO balance — the SAME card the driver portal shows. Office staff (Sara) land on this Time screen, not\n the driver portal, so their PTO balance was visible nowhere even though the rates are set and they carry a\n balance. Same accruedFor calc as payroll, so it can't disagree. */}\n \n\n {/* PTO */}\n \n

Time off

\n
\n {isAdmin && (\n \n )}\n \n \n \n \n setForm(f => ({ ...f, note: e.target.value }))} style={{ flex: 1, minWidth: '120px' }} />\n \n
\n {pto.length === 0 ?
No requests.
: pto.map(r => (\n
\n
\n {/* A row now belongs to a login OR a PIN-only driver, and the name map already answers for both. */}\n {people[r.user_id || r.driver_id] || 'Member'}\n · {r.start_date}{r.end_date !== r.start_date ? `–${r.end_date}` : ''} · {r.kind}{r.hours ? ` · ${r.hours}h` : ''}{r.note ? ` · ${r.note}` : ''}\n
\n
\n {r.status}\n {isAdmin && r.status === 'pending' && <>\n \n \n }\n {(isAdmin || r.user_id === profile.id) && }\n
\n
\n ))}\n
\n
\n )\n}\n","import { supabase } from './supabase'\n\n// Time-clock network restriction, edited in Site Settings.\n//\n// The values live in org_clock_settings, ONE ROW PER ORG since 2026-10-12 (it was a single app_secrets pair shared by\n// every company). The table is sealed -- RLS on, no policies, no grants -- so this goes through admin-gated SECURITY\n// DEFINER RPCs that act on the caller's own org. The row also holds the org's kiosk code (see lib/driverClock.js).\n\nexport async function getClockIpSettings() {\n const { data, error } = await supabase.rpc('get_clock_ip_settings')\n if (error) return { error: error.message }\n return { enabled: !!data?.enabled, ips: data?.ips || '', kioskCode: data?.kiosk_code || null }\n}\n\nexport async function setClockIpSettings(enabled, ips) {\n const { error } = await supabase.rpc('set_clock_ip_settings', { p_enabled: !!enabled, p_ips: ips || '' })\n return { ok: !error, error: error?.message }\n}\n\n// The caller's public IP, as the server sees it. Nobody knows their own egress address, and getting it wrong locks the\n// shop out of the clock -- so the settings screen offers to fill it in rather than asking someone to go find it.\n// The `clock` function already reports it: called with no punch kind it returns current state plus the observed IP.\nexport async function getMyIp() {\n try {\n const { data, error } = await supabase.functions.invoke('clock', { body: {} })\n if (error) return { error: error.message }\n return { ip: data?.ip || null }\n } catch (e) {\n return { error: String(e?.message || e) }\n }\n}\n","// THE APP SCREENSHOT MANIFEST — one list, imported by everything that shows app imagery: the gallery modal, and the\n// Feature List's per-section strips. Its own module rather than a constant hanging off the gallery component, because\n// a file that exports both a component and a constant breaks Fast Refresh (react-refresh/only-export-components) and\n// because two surfaces now depend on this list — it is shared data, not a detail of one screen.\n//\n// Images are static assets in `public/screenshots` (originals in `docs/screenshots`). `src` is the public path, so\n// adding one here is the whole job of adding it to the gallery; wiring it to a Feature List section is a separate,\n// deliberate step in FeatureListScreen's SECTION_SHOTS map.\nexport const SHOTS = [\n { src: '/screenshots/03-dispatch-board.png', title: 'Dispatch board' },\n { src: '/screenshots/10-lost-alert.png', title: 'Lost-driver alert' },\n { src: '/screenshots/05-en-route.png', title: 'En route tracking' },\n { src: '/screenshots/04-time-toggle.png', title: 'Delivery-time reporting' },\n { src: '/screenshots/06-drivers-cards.png', title: 'Driver cards' },\n { src: '/screenshots/07-drivers-list.png', title: 'Drivers' },\n { src: '/screenshots/02-tour.png', title: 'Guided tour' },\n { src: '/screenshots/08-settings.png', title: 'Settings' },\n { src: '/screenshots/09-help.png', title: 'Help center' },\n { src: '/screenshots/01-login.png', title: 'Sign in' },\n]\n","import { useState } from 'react'\nimport { SHOTS } from './screenshots'\n\n// In-app feature screenshot gallery. The image list lives in ./screenshots.js — the Feature List's per-section strips\n// read the same manifest. Opened from the Feature List page and Site Settings. A grid of thumbnails; click one to\n// view it large.\n\n// The full-size viewer, pulled out as its own export so the Feature List's inline strips reuse it rather than shipping\n// a second copy of the same overlay. One zoom behaviour everywhere an app screenshot is shown.\nexport function ScreenshotZoom({ shot, onClose }) {\n if (!shot) return null\n return (\n
\n {shot.title}\n
{shot.title}
\n
\n )\n}\n\nexport default function ScreenshotGallery({ open, onClose }) {\n const [zoom, setZoom] = useState(null) // a SHOT being viewed large\n if (!open) return null\n return (\n
\n
e.stopPropagation()} style={{ maxWidth: '1040px', width: '100%', margin: '0 auto', background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '14px', padding: '1.25rem' }}>\n
\n

📸 Route Now — Screenshots

\n \n
\n

A quick visual tour of the app. Click any image to view it full size.

\n
\n {SHOTS.map((s) => (\n \n ))}\n
\n
\n setZoom(null)} />\n
\n )\n}\n","import { useEffect, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { Button, Input } from '../ui'\nimport { orderInboxAddress, parseSenderList } from '../../lib/orderImport'\n\n// ORDER EMAIL-IN (2026-10-15, legacy order capture — gap 1 of docs/competitive/bringg-deliverytrack-gap.md). The\n// no-code door for an order system that can EMAIL an invoice or an export but will never call the API: turn it on, and\n// mail sent to the org's own address becomes orders in Unassigned (supabase/functions/orders-inbound).\n//\n// ITS OWN READ, NOT A COLUMN IN THE SCREEN'S BIG SELECT. Until orgs_order_inbox.sql is applied these columns do not\n// exist, and one unknown column in that select fails the WHOLE settings load — every toggle on the page would show\n// its default. Here a failed read just hides this card.\nexport default function OrderInboxCard({ orgId, styles }) {\n const { card, h2, label, hint, savedFlash, toggleSwitch, toggleKnob } = styles\n const [ready, setReady] = useState(false)\n const [enabled, setEnabled] = useState(false)\n const [token, setToken] = useState('')\n const [senders, setSenders] = useState('')\n const [events, setEvents] = useState([])\n const [flash, setFlash] = useState(null)\n const [err, setErr] = useState(null)\n\n useEffect(() => {\n if (!orgId) return\n let live = true\n // THE TOKEN IS NOT IN THIS SELECT (2026-10-26). It is the lock on the org's inbox address — with no sender list,\n // anyone holding it can mail orders onto the board — and every member, drivers included, could read it. It now\n // comes from org_integration_secrets(), admin/owner only, like the API key and webhook secret.\n Promise.all([\n supabase.from('organizations').select('order_inbox_enabled, order_inbox_senders').eq('id', orgId).single(),\n supabase.rpc('org_integration_secrets'),\n ]).then(([{ data, error }, sec]) => {\n if (!live || error || !data) return\n const row = Array.isArray(sec.data) ? sec.data[0] : sec.data\n setEnabled(!!data.order_inbox_enabled)\n setToken(row?.order_inbox_token || '')\n setSenders((data.order_inbox_senders || []).join(', '))\n setReady(true)\n })\n supabase.from('order_inbox_events').select('id, from_addr, subject, status, created_count, duplicate_count, failed_count, detail, created_at')\n .eq('org_id', orgId).order('created_at', { ascending: false }).limit(10)\n .then(({ data }) => { if (live && data) setEvents(data) })\n return () => { live = false }\n }, [orgId])\n\n async function save(key, patch) {\n setErr(null)\n const { error } = await supabase.from('organizations').update(patch).eq('id', orgId)\n if (error) { setErr(`Could not save: ${error.message}`); return false }\n setFlash(key); setTimeout(() => setFlash((k) => (k === key ? null : k)), 2500)\n return true\n }\n // MINTED ON THE SERVER (ensure_org_integration_secret), not in the browser: the column is being made unwritable from\n // here. Returns the token, or null after saying why.\n async function mint(rotate) {\n setErr(null)\n const { data, error } = await supabase.rpc('ensure_org_integration_secret', { p_kind: 'order_inbox_token', p_rotate: !!rotate })\n if (error || !data) { setErr(`Could not ${rotate ? 'make a new' : 'set up the'} address: ${error?.message || 'no address came back'}`); return null }\n return data\n }\n async function toggle() {\n const n = !enabled\n // The address is minted the first time it is turned on and kept after, so turning it off and on again does not\n // break the forwarding rule someone set up in the order system. Minted BEFORE the switch is saved, so \"on\" is\n // never stored without an address.\n const t = token || (n ? await mint(false) : '')\n if (n && !t) return\n if (await save('toggle', { order_inbox_enabled: n })) { setEnabled(n); setToken(t) }\n }\n async function rotate() {\n if (!window.confirm('Make a new address? The old one stops working immediately — update the order system to send to the new one.')) return\n const t = await mint(true)\n if (t) { setToken(t); setFlash('rotate'); setTimeout(() => setFlash((k) => (k === 'rotate' ? null : k)), 2500) }\n }\n async function saveSenders() {\n const list = parseSenderList(senders)\n if (await save('senders', { order_inbox_senders: list })) setSenders(list.join(', '))\n }\n\n if (!ready) return null\n const address = orderInboxAddress(token)\n return (\n
\n

Order email-in (no-code order capture)

\n

\n For an order system that can email but can't use the API. Have it send each invoice — or a CSV/Excel export of the day's orders — to your address below, and the orders land in Unassigned within about two minutes. Off by default.\n

\n
\n \n {enabled ? 'On' : 'Off'}\n {(flash === 'toggle' || flash === 'rotate') && ✓ Saved for your team}\n
\n {err &&

{err}

}\n\n {enabled && (\n <>\n \n {address}\n
\n \n \n
\n

\n What it reads: a CSV or Excel file with a header row (invoice #, customer, address, city, state, zip, phone, COD, notes), a PDF invoice, a photo of an invoice, or an invoice typed in the email itself. Each address is checked on the dispatch board like any other new order.\n

\n\n \n setSenders(e.target.value)} placeholder=\"orders@yourstore.com, @yourstore.com\" />\n
\n \n {flash === 'senders' && ✓ Saved}\n
\n

Leave empty to accept mail from anyone who has the address. Write @yourstore.com to allow a whole domain.

\n\n \n {events.length === 0\n ?

Nothing yet. Send a test email to the address above.

\n : (\n
\n {events.map((e) => (\n
\n {new Date(e.created_at).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}\n {' · '}{e.from_addr || 'unknown sender'}{e.subject ? ` · ${e.subject}` : ''}\n
{inboxEventLine(e)}
\n
\n ))}\n
\n )}\n \n )}\n
\n )\n}\n\n// One plain sentence per received email — what the dispatcher needs to know is whether the orders arrived, and if\n// not, the reason in words they can act on.\nfunction inboxEventLine(e) {\n if (e.status === 'refused') return 'Not accepted — the sender is not on the list above.'\n if (e.status === 'processing') return 'Still reading…'\n const errs = (e.detail?.files || []).filter((f) => f.error).map((f) => `${f.file}: ${f.error}`)\n const parts = []\n if (e.created_count) parts.push(`${e.created_count} order${e.created_count === 1 ? '' : 's'} added`)\n if (e.duplicate_count) parts.push(`${e.duplicate_count} already on the board`)\n if (e.failed_count) parts.push(`${e.failed_count} could not be added`)\n if (errs.length) parts.push(errs.join('; '))\n if (e.status === 'error' && e.detail?.error) parts.push(`stopped: ${e.detail.error}`)\n return parts.length ? parts.join(' · ') : 'No orders found in that email.'\n}\n","import { supabase } from './supabase'\n\n// Customer image library — the \"Settings → Images\" area. Objects are namespaced by org id in the path so each org\n// only sees its own. Public bucket, so getPublicUrl gives a shareable link the customer can use anywhere (branding,\n// their own docs, a designer's assets, etc.). Mirrors the uploadReceipt / uploadChatImage pattern.\nconst BUCKET = 'org-media'\n\nexport async function uploadOrgImage(orgId, file) {\n const ext = (file?.name?.split('.').pop() || file?.type?.split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '').toLowerCase() || 'png'\n const path = `${orgId || 'org'}/${crypto.randomUUID()}.${ext}`\n const { error } = await supabase.storage.from(BUCKET).upload(path, file, { contentType: file?.type || 'image/png', upsert: false })\n if (error) return { error: error.message }\n const { data } = supabase.storage.from(BUCKET).getPublicUrl(path)\n return { url: data?.publicUrl, path }\n}\n\nexport async function listOrgImages(orgId) {\n const { data, error } = await supabase.storage.from(BUCKET).list(orgId || 'org', { limit: 100, sortBy: { column: 'created_at', order: 'desc' } })\n if (error) return []\n return (data || []).filter((o) => o.id).map((o) => {\n const path = `${orgId || 'org'}/${o.name}`\n return { name: o.name, path, url: supabase.storage.from(BUCKET).getPublicUrl(path).data?.publicUrl }\n })\n}\n\nexport async function deleteOrgImage(path) {\n const { error } = await supabase.storage.from(BUCKET).remove([path])\n return { error: error?.message }\n}\n","// One line of plain English per webhook delivery row, for Site Settings' \"Recent deliveries\" list. Pure so\n// scripts/webhook-retries.test.mjs can pin the wording against each status the worker can leave a row in.\n\nfunction ago(iso, now) {\n const s = Math.round((new Date(iso).getTime() - now) / 1000)\n const a = Math.abs(s)\n const txt = a < 90 ? `${Math.max(1, a)}s` : a < 5400 ? `${Math.round(a / 60)}m` : a < 129600 ? `${Math.round(a / 3600)}h` : `${Math.round(a / 86400)}d`\n return s >= 0 ? `in ${txt}` : `${txt} ago`\n}\n\nexport function describeDelivery(r, now = Date.now()) {\n const host = r.url_host ? ` to ${r.url_host}` : ''\n const tries = `${r.attempts} ${r.attempts === 1 ? 'attempt' : 'attempts'}`\n const last = r.last_status_code ? `HTTP ${r.last_status_code}` : (r.last_error || 'no response')\n if (r.status === 'delivered') return { label: 'Delivered', detail: `Delivered${host} after ${tries}` }\n if (r.status === 'pending') {\n const next = r.next_attempt_at ? `, next try ${ago(r.next_attempt_at, now)}` : ''\n return { label: 'Retrying', detail: `${last}${host} — ${tries}${next}` }\n }\n return { label: 'Failed', detail: `${r.last_error || last}${host} — gave up after ${tries}` }\n}\n","import { useCallback, useEffect, useState } from 'react'\nimport { supabase } from '../../lib/supabase'\nimport { Button, Badge } from '../ui'\nimport { describeDelivery } from '../../lib/webhookLog'\n\n// Recent webhook deliveries — the last 50 events Route Now tried to POST to this org's endpoint, with the outcome of\n// the latest attempt and when the next retry is due. Lives under the webhook URL in Site Settings, because \"did my\n// endpoint get it?\" is the first question anyone integrating asks, and until this existed only our function logs knew.\n//\n// Read straight from public.webhook_deliveries (RLS: staff of this org). `body` is never selected — `retryable` says\n// whether a resend is possible without shipping every payload to the browser. \"Retry now\" calls the\n// retry_webhook_delivery RPC, which only re-queues: the worker sends it within a minute, signed with the server-side\n// secret the browser never holds.\n\nconst COLS = 'id, event, url_host, status, attempts, max_attempts, last_status_code, last_error, last_attempt_at, next_attempt_at, delivered_at, created_at, retryable'\nconst TONE = { delivered: 'accent', pending: 'warn', failed: 'danger' }\n\nexport default function WebhookDeliveryLog({ orgId }) {\n const [rows, setRows] = useState(null)\n const [err, setErr] = useState(null)\n const [busy, setBusy] = useState(null)\n\n const load = useCallback(async () => {\n if (!orgId) return\n const { data, error } = await supabase.from('webhook_deliveries').select(COLS)\n .eq('org_id', orgId).order('created_at', { ascending: false }).limit(50)\n // A missing table (migration not applied yet) reads as \"nothing to show\", not as a broken settings page.\n if (error) { setErr(error.message || 'Could not load the delivery log.'); setRows([]); return }\n setErr(null); setRows(data || [])\n }, [orgId])\n\n useEffect(() => { load() }, [load])\n\n async function retry(id) {\n setBusy(id)\n const { error } = await supabase.rpc('retry_webhook_delivery', { p_id: id })\n setBusy(null)\n if (error) { setErr(error.message || 'Retry could not be queued.'); return }\n load()\n }\n\n return (\n
\n
\n Recent deliveries\n \n
\n {err &&

{err}

}\n {rows === null &&

Loading…

}\n {rows && rows.length === 0 && !err &&

No deliveries yet. Events appear here as drivers dispatch, deliver and finish runs.

}\n {rows && rows.length > 0 && (\n
\n {rows.map((r, i) => {\n const d = describeDelivery(r)\n return (\n
\n {d.label}\n {r.event}\n {new Date(r.created_at).toLocaleString()}\n {d.detail}\n {r.retryable && r.status !== 'delivered' && (\n \n )}\n
\n )\n })}\n
\n )}\n
\n )\n}\n\nconst muted = { color: 'var(--text-2)', fontSize: '14px', margin: 0 }\n","import { useState } from 'react'\nimport { usePieces, addPiece, updatePiece, movePiece, pieceNameProblem } from '../../lib/marketingPieces'\nimport { Button } from '../ui'\n\n// MARKETING PIECES — the flyers the reps leave at a shop (Brian, 2026-10-20: \"we have specific flyers that we hand out\n// that change over time\"). Lives under the Win-back visits switch in Site Settings, the place every marketing-visit\n// setting already is. Add, rename, reorder, and RETIRE — a retired piece leaves every dropdown but stays on the visits\n// that recorded it (each visit keeps the name it was left under). Nothing is ever deleted from here.\n// An org with no list is given the four defaults (CAT, RAD, AC, Info flyer) the first time this opens.\nexport default function MarketingPiecesEditor({ orgId }) {\n const { rows, loaded } = usePieces(orgId)\n const [draft, setDraft] = useState('')\n const [editing, setEditing] = useState(null) // { id, name }\n const [err, setErr] = useState(null)\n const [busy, setBusy] = useState(false)\n const active = rows.filter((r) => r.active !== false && r.kind !== 'visit_only')\n const retired = rows.filter((r) => r.active === false && r.kind !== 'visit_only')\n\n async function run(fn) { setBusy(true); setErr(null); const r = await fn(); setBusy(false); if (r && !r.ok) setErr(r.error || 'That did not save.'); return r }\n async function add() {\n const problem = pieceNameProblem(draft, rows)\n if (problem) { setErr(problem); return }\n const r = await run(() => addPiece(orgId, draft))\n if (r?.ok) setDraft('')\n }\n async function saveRename() {\n const problem = pieceNameProblem(editing.name, rows, editing.id)\n if (problem) { setErr(problem); return }\n const r = await run(() => updatePiece(orgId, editing.id, { name: editing.name.trim().replace(/\\s+/g, ' ') }))\n if (r?.ok) setEditing(null)\n }\n\n const row = { display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.45rem 0', borderBottom: '1px solid var(--border)', flexWrap: 'wrap' }\n const icon = { background: 'transparent', border: '1px solid var(--border)', borderRadius: '6px', color: 'var(--text-2)', cursor: 'pointer', fontSize: '13px', fontWeight: 700, padding: '3px 8px', minHeight: '30px' }\n const input = { flex: '1 1 160px', minWidth: 0, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '15px', padding: '0.45rem 0.6rem' }\n\n return (\n
\n

📄 Marketing pieces

\n

\n The flyers your reps leave. They pick one from a dropdown on every visit, and you can preassign one per stop when planning. Retire a piece when it is out of date — it leaves the dropdowns but stays on past visits.\n

\n {!loaded ?
Loading…
: (\n <>\n {active.length === 0 &&
No active pieces — reps will only see “None”.
}\n {active.map((r, i) => (\n
\n {editing?.id === r.id ? (\n <>\n setEditing({ ...editing, name: e.target.value })}\n onKeyDown={(e) => { if (e.key === 'Enter') saveRename(); if (e.key === 'Escape') setEditing(null) }} style={input} />\n \n \n \n ) : (\n <>\n \n {r.name}{r.kind === 'coupon' && · coupon}\n \n \n \n \n \n \n )}\n
\n ))}\n
\n setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') add() }} style={input} />\n \n
\n {err &&
{err}
}\n {retired.length > 0 && (\n
\n
Retired
\n {retired.map((r) => (\n
\n {r.name}\n \n
\n ))}\n
\n )}\n \n )}\n
\n )\n}\n","import { useEffect, useState } from 'react'\nimport { useSearchParams } from 'react-router-dom'\nimport { supabase } from '../../lib/supabase'\nimport { ACCENT_PRESETS, DEFAULT_ACCENT, applyAccent } from '../../lib/theme'\nimport { PAGES, DEFAULT_ROLE_PAGES, canViewPayroll } from '../../lib/pageAccess'\nimport { getClockIpSettings, setClockIpSettings, getMyIp } from '../../lib/clockIpSettings'\nimport { depotCoords } from '../../lib/geocode'\nimport { Button, Input } from '../ui'\nimport { ChevronDown } from 'lucide-react'\nimport ScreenshotGallery from '../common/ScreenshotGallery'\nimport OrderInboxCard from './OrderInboxCard'\nimport { uploadOrgImage, listOrgImages, deleteOrgImage } from '../../lib/orgMedia'\nimport WebhookDeliveryLog from './WebhookDeliveryLog'\nimport MarketingPiecesEditor from './MarketingPiecesEditor'\nimport { FEATURES } from '../../lib/features'\nimport { isEmailable } from '../../lib/stopText'\n\n// Site Settings — org-level configuration for the whole team: organization name, routing rules (handling time + the\n// route time cap), locations, dispatch board layout, and brand color. Admins only. (User-level settings — team, users —\n// live on the separate User Settings page.)\n\n// Section nav for the page — tab-style (picking a section shows ONLY that section; deliberately not scroll-to-anchor\n// jump links). Same pill language as Trip History's Trip History / Delivery Stats segmented control. Every settings\n// card lives in exactly one section; deep-linkable via ?section= (e.g. /site-setup?section=timeclock).\nconst SECTIONS = [\n { key: 'company', label: 'Company & branding' },\n { key: 'routing', label: 'Dispatch & routing' },\n { key: 'drivers', label: 'Drivers & deliveries' },\n { key: 'customers', label: 'Customers & tracking' },\n { key: 'alerts', label: 'Alerts & messages' },\n { key: 'timeclock', label: 'Time clock & payroll' },\n { key: 'integrations', label: 'Access & integrations' },\n]\n\n// What to call each setting when its save is refused, keyed by the same string that drives the ✓ flash. A message\n// saying \"That setting was not saved\" on a page of thirty settings tells nobody which one, and the failure a reader\n// most needs to act on is the one they just clicked. Anything not named here falls back to \"That setting\".\nconst ORG_SETTING_LABELS = {\n pickupEmail: 'The pickup reminder email address',\n renewalEmail: 'The renewal reminder email address',\n returns: 'Returns',\n addrCapture: 'Address capture',\n savedAddr: 'Saved addresses',\n pod: 'Proof of delivery',\n barcode: 'Barcode scanning',\n checklist: 'The driver checklist',\n winback: 'Marketing visits',\n checklistremind: 'The checklist reminder',\n remindcfg: 'The checklist reminder time and message',\n cod: 'Cash on delivery',\n exceptions: 'Delivery exceptions',\n afterhours: 'After-hours alerts',\n afterhoursCfg: 'The after-hours alert settings',\n fleetShift: 'Shift-only tracking',\n shiftCfg: 'The shift window',\n pingKeep: 'How long position history is kept',\n customers: 'Customers',\n recurring: 'Recurring orders',\n capacity: 'Capacity routing',\n ratings: 'Ratings',\n podEmail: 'Delivery confirmation emails',\n whitelabel: 'White-labelling',\n logo: 'The logo',\n alertmsgs: 'The alert messages',\n driverpay: 'Driver pay',\n payrates: 'The pay rates',\n webhooks: 'Webhooks',\n webhookUrl: 'The webhook URL',\n billing: 'Billing',\n api: 'API access',\n}\n\nexport default function SiteSetupScreen({ profile, reloadProfile }) {\n // Org name + routing\n const [orgName, setOrgName] = useState('')\n const [stopMinutes, setStopMinutes] = useState('8')\n const [capMinutes, setCapMinutes] = useState('60')\n const [idleMinutes, setIdleMinutes] = useState('12')\n const [lostMinutes, setLostMinutes] = useState('20')\n const [stationaryMinutes, setStationaryMinutes] = useState('30')\n const [reviewMinutes, setReviewMinutes] = useState('20')\n // DoorDash nudge — suggests a courier for a close order that has been sitting and has nothing nearby to be\n // batched with, i.e. one heading for a dedicated single-truck round trip.\n const [ddNudge, setDdNudge] = useState(false)\n const [ddMiles, setDdMiles] = useState('20')\n const [ddWait, setDdWait] = useState('20')\n const [ddCost, setDdCost] = useState('20')\n const [ddBatch, setDdBatch] = useState('5')\n const [ddBack, setDdBack] = useState('15')\n // Time-clock network restriction. Loaded through an RPC (app_secrets is sealed), so it has its own load/save\n // rather than riding along with the organizations row.\n const [clockIpOn, setClockIpOn] = useState(true)\n const [clockIps, setClockIps] = useState('')\n const [clockIpMsg, setClockIpMsg] = useState(null)\n const [clockIpBusy, setClockIpBusy] = useState(false)\n const [kioskCode, setKioskCode] = useState(null)\n const [kioskCopied, setKioskCopied] = useState(false)\n // The whole stored object, not just the fields this screen edits: saving here must not drop a key it does not show.\n const [ptoByTypeRaw, setPtoByTypeRaw] = useState({})\n const [ptoPT, setPtoPT] = useState('0')\n const [ptoSeasonal, setPtoSeasonal] = useState('0')\n const [ptoDefault, setPtoDefault] = useState('0')\n const [dispatcherPages, setDispatcherPages] = useState(DEFAULT_ROLE_PAGES.dispatcher)\n const [savingName, setSavingName] = useState(false)\n // THE BANNER HAS TO BE ABLE TO SAY \"NO\". It was one green box carrying both outcomes, so every `Could not save`\n // on this screen was already being drawn in success colours. `setMsg` keeps its name and all its existing call\n // sites — it just clears the failure flag — and `saveFailed` is its opposite number.\n const [msg, setMsgText] = useState(null)\n const [msgFailed, setMsgFailed] = useState(false)\n const setMsg = (text) => { setMsgFailed(false); setMsgText(text) }\n // A save that did not land. The screen's toggle-style savers set their control's local state BEFORE the write, so\n // on failure the switch on screen no longer matches the database — say that out loud rather than leaving someone\n // looking at a setting that isn't stored.\n const saveFailed = (what, error) => {\n setMsgFailed(true)\n setMsgText(`${what} was NOT saved: ${error?.message || 'the database refused the change'}. What you see on screen is not what's stored — reload the page to see the real setting.`)\n }\n\n // Locations\n const [locations, setLocations] = useState([])\n const [editLocations, setEditLocations] = useState({})\n const [showAddLocation, setShowAddLocation] = useState(false)\n const [newLocName, setNewLocName] = useState('')\n const [newLocAddr, setNewLocAddr] = useState('')\n\n // Brand color (collapsible) + board layout\n const [color, setColor] = useState(DEFAULT_ACCENT)\n const [saved, setSaved] = useState(false)\n const [saving, setSaving] = useState(false)\n const [colorOpen, setColorOpen] = useState(false)\n const [layout, setLayout] = useState('2up')\n const [layoutSaving, setLayoutSaving] = useState(false)\n const [layoutSaved, setLayoutSaved] = useState(false)\n\n // Pre-seed routes (default off)\n const [preseed, setPreseed] = useState(false)\n const [preseedSaving, setPreseedSaving] = useState(false)\n const [preseedSaved, setPreseedSaved] = useState(false)\n\n // Customer delivery tracking (default off) + mode ('single' | 'multi')\n const [custTrack, setCustTrack] = useState(false)\n const [custMode, setCustMode] = useState('multi')\n const [custName, setCustName] = useState('')\n const [custSaving, setCustSaving] = useState(false)\n const [custSaved, setCustSaved] = useState(false)\n\n // Driver capture + integrations — each independently activatable, all default off.\n const [pod, setPod] = useState(false)\n const [barcode, setBarcode] = useState(false)\n const [cod, setCod] = useState(false)\n const [exceptions, setExceptions] = useState(false)\n const [ahEnabled, setAhEnabled] = useState(false)\n const [ahPhone, setAhPhone] = useState('')\n const [pickupEmail, setPickupEmail] = useState('') // where the not-ready pickup reminder goes\n const [renewalEmail, setRenewalEmail] = useState('') // registration_email_to — insurance + plates renewal reminders\n const [renewalErr, setRenewalErr] = useState(null)\n const [returnsOn, setReturnsOn] = useState(false) // returns_enabled — the ↩ return toggle on board chips\n const [ahOpen, setAhOpen] = useState('07:00')\n const [ahClose, setAhClose] = useState('18:00')\n const [ahDays, setAhDays] = useState([1, 2, 3, 4, 5, 6])\n const [ahThreshold, setAhThreshold] = useState('300')\n const [ahTest, setAhTest] = useState(null) // null | 'sending' | 'sent' | \n // Shift-only tracking — a company tracker in a driver's PERSONAL vehicle is watched ONLY during their shift; outside\n // it Route Now ingests, stores and shows nothing. shift_tracking_enabled is a MASTER flag we set for the org (not\n // self-serve) — it gates whether this whole card is even shown. Inside it: a fleet-wide default window that every GPS\n // vehicle follows unless it carries its own window (set per vehicle on the Vehicles screen).\n const [shiftTrackOn, setShiftTrackOn] = useState(false)\n const [fleetShiftDefault, setFleetShiftDefault] = useState(false)\n // How long driver position history is kept before the nightly sweep deletes it. A retention control, so it is a\n // number the customer sets rather than one we choose for them — some shops want a fortnight, some want the year.\n const [pingKeepDays, setPingKeepDays] = useState('30')\n const [shiftOpen, setShiftOpen] = useState('07:00')\n const [shiftClose, setShiftClose] = useState('18:00')\n const [shiftDays, setShiftDays] = useState([1, 2, 3, 4, 5, 6])\n const [checklistEn, setChecklistEn] = useState(false)\n const [winbackEn, setWinbackEn] = useState(false)\n const [remindEn, setRemindEn] = useState(false)\n const [remindTime, setRemindTime] = useState('07:30')\n const [remindMsg, setRemindMsg] = useState('')\n const [customersEn, setCustomersEn] = useState(false)\n const [recurringEn, setRecurringEn] = useState(false)\n const [capacityRouting, setCapacityRouting] = useState(false)\n const [ratingsEn, setRatingsEn] = useState(false)\n // Delivery confirmation email to the shop. `emailEntitled` is the Email sending entitlement (organizations.email_enabled),\n // which only Route Now can switch on; null until read, so the hint never claims \"not available\" before we know.\n const [podEmailEn, setPodEmailEn] = useState(false)\n const [emailEntitled, setEmailEntitled] = useState(null)\n const [whitelabel, setWhitelabel] = useState(false)\n const [logoUrl, setLogoUrl] = useState('')\n const [galleryOpen, setGalleryOpen] = useState(false)\n const [orgImages, setOrgImages] = useState([])\n const [imgBusy, setImgBusy] = useState(false)\n const [idleMsg, setIdleMsg] = useState('')\n const [lostMsg, setLostMsg] = useState('')\n const [stationaryMsg, setStationaryMsg] = useState('')\n const [driverPay, setDriverPay] = useState(false)\n const [payPerStop, setPayPerStop] = useState('')\n const [payPerMile, setPayPerMile] = useState('')\n const [webhooks, setWebhooks] = useState(false)\n const [webhookUrl, setWebhookUrl] = useState('')\n const [webhookSecret, setWebhookSecret] = useState('')\n const [apiEnabled, setApiEnabled] = useState(false)\n const [apiKey, setApiKey] = useState('')\n const [billingEnabled, setBillingEnabled] = useState(false)\n const [plan, setPlan] = useState('trial')\n const [trialEndsAt, setTrialEndsAt] = useState(null)\n const [featSaved, setFeatSaved] = useState(null) // which feature key just saved, for the ✓ flash\n\n // Show/hide the manual \"Add an Address\" capture box on the dispatch board (default on; shops like 703 that only\n // PhotoScan turn it off so it's absent from the board).\n const [addrCapture, setAddrCapture] = useState(true)\n\n // Show/hide the Saved Addresses card, which sits directly under \"Scan a printed address\" on the board. Independent of\n // addrCapture — a shop can keep its pinned address book while hiding manual entry, or the reverse.\n const [savedAddr, setSavedAddr] = useState(true)\n\n // Which settings section is showing (tab-style — one section renders at a time). ?section= deep-links straight to\n // one and is re-honored on in-page navigation, mirroring HistoryScreen's ?view= pattern. NOTE: all data loading\n // (org row, locations, images, clock IPs) stays unconditional above — hiding a section never skips a fetch.\n const [searchParams] = useSearchParams()\n const urlSection = searchParams.get('section')\n const [section, setSection] = useState(() => (SECTIONS.some(s => s.key === urlSection) ? urlSection : SECTIONS[0].key))\n useEffect(() => { if (SECTIONS.some(s => s.key === urlSection)) setSection(urlSection) }, [urlSection])\n\n // Hydrate from the DB (source of truth) so saved values still show after navigating away and back.\n useEffect(() => {\n if (!profile?.org_id) return\n supabase.from('organizations').select('name, stop_minutes, route_cap_minutes, idle_alert_minutes, lost_alert_minutes, review_threshold_minutes, doordash_nudge_enabled, doordash_driver_back_minutes, doordash_max_miles, doordash_wait_minutes, doordash_avg_cost, doordash_batch_radius_miles, idle_alert_message, lost_alert_message, stationary_alert_minutes, stationary_alert_message, pto_accrual_rate, pto_accrual_by_type, role_pages, theme_color, board_layout, preseed_enabled, customer_tracking_enabled, customer_tracking_mode, customer_facing_name, pod_enabled, barcode_enabled, cod_enabled, exceptions_enabled, returns_enabled, checklist_enabled, winback_enabled, customers_enabled, recurring_enabled, capacity_routing_enabled, ratings_enabled, whitelabel_enabled, logo_url, driver_pay_enabled, pay_per_stop, pay_per_mile, webhooks_enabled, webhook_url, api_enabled, billing_enabled, plan, trial_ends_at, afterhours_alert_enabled, afterhours_alert_phone, afterhours_open, afterhours_close, afterhours_days, afterhours_threshold_m, shift_tracking_enabled, fleet_shift_default, fleet_shift_open, fleet_shift_close, fleet_shift_days, address_capture_enabled, saved_addresses_enabled, checklist_remind_enabled, checklist_remind_time, checklist_remind_message, ping_retention_days, pickup_email_to, registration_email_to').eq('id', profile.org_id).single()\n .then(({ data }) => {\n if (!data) return\n setOrgName(data.name || '')\n setStopMinutes(String(data.stop_minutes ?? 8))\n setCapMinutes(String(data.route_cap_minutes ?? 60))\n setIdleMinutes(String(data.idle_alert_minutes ?? 12))\n setLostMinutes(String(data.lost_alert_minutes ?? 20))\n setStationaryMinutes(String(data.stationary_alert_minutes ?? 30))\n setReviewMinutes(String(data.review_threshold_minutes ?? 20))\n setPingKeepDays(String(data.ping_retention_days ?? 30))\n setDdNudge(!!data.doordash_nudge_enabled)\n setDdMiles(String(data.doordash_max_miles ?? 20))\n setDdWait(String(data.doordash_wait_minutes ?? 20))\n setDdCost(String(data.doordash_avg_cost ?? 20))\n setDdBatch(String(data.doordash_batch_radius_miles ?? 5))\n setDdBack(String(data.doordash_driver_back_minutes ?? 15))\n setIdleMsg(data.idle_alert_message || '')\n setStationaryMsg(data.stationary_alert_message || '')\n setLostMsg(data.lost_alert_message || '')\n setPtoDefault(String(data.pto_accrual_rate ?? 0))\n { const t = data.pto_accrual_by_type || {}; setPtoByTypeRaw(t); setPtoPT(String(t.part_time ?? 0)); setPtoSeasonal(String(t.seasonal ?? 0)) }\n setDispatcherPages(Array.isArray(data.role_pages?.dispatcher) ? data.role_pages.dispatcher : DEFAULT_ROLE_PAGES.dispatcher)\n const c = data.theme_color || DEFAULT_ACCENT; setColor(c); applyAccent(c)\n setLayout(data.board_layout || '2up')\n setPreseed(!!data.preseed_enabled)\n setAddrCapture(data.address_capture_enabled !== false)\n setSavedAddr(data.saved_addresses_enabled !== false)\n setCustTrack(!!data.customer_tracking_enabled)\n setCustMode(data.customer_tracking_mode || 'multi')\n setCustName(data.customer_facing_name || '')\n setPod(!!data.pod_enabled)\n setBarcode(!!data.barcode_enabled)\n setCod(!!data.cod_enabled)\n setExceptions(!!data.exceptions_enabled)\n setAhEnabled(!!data.afterhours_alert_enabled)\n setAhPhone(data.afterhours_alert_phone || '')\n setPickupEmail(data.pickup_email_to || '')\n setRenewalEmail(data.registration_email_to || '')\n setReturnsOn(!!data.returns_enabled)\n setAhOpen((data.afterhours_open || '07:00:00').slice(0, 5))\n setAhClose((data.afterhours_close || '18:00:00').slice(0, 5))\n setAhDays(Array.isArray(data.afterhours_days) ? data.afterhours_days : [1, 2, 3, 4, 5, 6])\n setAhThreshold(String(data.afterhours_threshold_m ?? 300))\n setShiftTrackOn(!!data.shift_tracking_enabled)\n setFleetShiftDefault(!!data.fleet_shift_default)\n setShiftOpen((data.fleet_shift_open || '07:00:00').slice(0, 5))\n setShiftClose((data.fleet_shift_close || '18:00:00').slice(0, 5))\n setShiftDays(Array.isArray(data.fleet_shift_days) ? data.fleet_shift_days : [1, 2, 3, 4, 5, 6])\n setChecklistEn(!!data.checklist_enabled)\n setWinbackEn(!!data.winback_enabled)\n setRemindEn(!!data.checklist_remind_enabled)\n setRemindTime((data.checklist_remind_time || '07:30:00').slice(0, 5))\n setRemindMsg(data.checklist_remind_message || '')\n setCustomersEn(!!data.customers_enabled)\n setRecurringEn(!!data.recurring_enabled)\n setCapacityRouting(!!data.capacity_routing_enabled)\n setRatingsEn(!!data.ratings_enabled)\n setWhitelabel(!!data.whitelabel_enabled)\n setLogoUrl(data.logo_url || '')\n setDriverPay(!!data.driver_pay_enabled)\n setPayPerStop(data.pay_per_stop != null ? String(data.pay_per_stop) : '')\n setPayPerMile(data.pay_per_mile != null ? String(data.pay_per_mile) : '')\n setWebhooks(!!data.webhooks_enabled)\n setWebhookUrl(data.webhook_url || '')\n setApiEnabled(!!data.api_enabled)\n setBillingEnabled(!!data.billing_enabled)\n setPlan(data.plan || 'trial')\n setTrialEndsAt(data.trial_ends_at || null)\n })\n // THE TWO INTEGRATION SECRETS ARE THEIR OWN, ADMIN-ONLY READ (2026-10-26). They were columns in the select above,\n // and that select is not what exposed them — `profiles … organizations(*)` put them in every member's browser,\n // drivers included. Both columns are now revoked from anon/authenticated; org_integration_secrets() answers only an\n // admin/owner of this org. A refusal leaves them blank ('—') rather than failing the rest of the page.\n supabase.rpc('org_integration_secrets').then(({ data, error }) => {\n if (error) return\n const row = Array.isArray(data) ? data[0] : data\n setWebhookSecret(row?.webhook_secret || '')\n setApiKey(row?.api_key || '')\n })\n // ITS OWN READ, NOT A COLUMN IN THE SELECT ABOVE. pod_email_enabled arrives with pod_email_to_shop.sql; one unknown\n // column fails that whole select and every setting on this page would hydrate as its default. Here it costs one card.\n supabase.from('organizations').select('email_enabled, pod_email_enabled').eq('id', profile.org_id).maybeSingle()\n .then(({ data, error }) => {\n if (error || !data) return\n setPodEmailEn(!!data.pod_email_enabled)\n setEmailEntitled(!!data.email_enabled)\n })\n supabase.from('locations').select('*').eq('org_id', profile.org_id).then(({ data }) => {\n setLocations(data || [])\n const edits = {}\n for (const l of data || []) edits[l.id] = { name: l.name, default_address: l.default_address }\n setEditLocations(edits)\n })\n }, [profile?.org_id])\n\n async function saveOrgName() {\n setSavingName(true); setMsg(null)\n const { error } = await supabase.from('organizations').update({ name: orgName }).eq('id', profile.org_id)\n setSavingName(false)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setMsg('Organization name saved.')\n reloadProfile?.() // refresh the app-wide profile so the header name updates immediately\n }\n\n async function saveRouting() {\n const sn = parseInt(stopMinutes, 10)\n const stops = Number.isFinite(sn) && sn >= 0 ? sn : 8\n const cn = parseInt(capMinutes, 10)\n const cap = Number.isFinite(cn) && cn > 0 ? cn : 60\n const idn = parseInt(idleMinutes, 10)\n const idle = Number.isFinite(idn) && idn > 0 ? idn : 12\n const lon = parseInt(lostMinutes, 10)\n const lost = Number.isFinite(lon) && lon > 0 ? lon : 20\n const stn = parseInt(stationaryMinutes, 10)\n const stationary = Number.isFinite(stn) && stn > 0 ? stn : 30\n const rvn = parseInt(reviewMinutes, 10)\n const review = Number.isFinite(rvn) && rvn > 0 ? rvn : 20\n const { error } = await supabase.from('organizations').update({ stop_minutes: stops, route_cap_minutes: cap, idle_alert_minutes: idle, lost_alert_minutes: lost, stationary_alert_minutes: stationary, review_threshold_minutes: review }).eq('id', profile.org_id)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setStopMinutes(String(stops)); setCapMinutes(String(cap)); setIdleMinutes(String(idle)); setStationaryMinutes(String(stationary)); setReviewMinutes(String(review))\n setMsg(`Routing saved — ${stops} min between stops, ${cap} min route cap, ${idle} min idle alert, ${review} min review threshold.`)\n reloadProfile?.() // so the dispatch board's cap toggle uses the new value right away\n }\n\n // Saved on its own rather than folded into Routing: this one authorises SPENDING MONEY, so it should be a\n // deliberate act with its own confirmation, not something that rides along with a stop-time tweak.\n async function saveDoorDash() {\n const pos = (v, dflt, max) => { const n = Number(v); return Number.isFinite(n) && n > 0 && n <= max ? n : dflt }\n const miles = pos(ddMiles, 20, 200)\n const wait = Math.round(pos(ddWait, 20, 1440))\n const cost = pos(ddCost, 20, 1000)\n const batch = Number.isFinite(Number(ddBatch)) && Number(ddBatch) >= 0 && Number(ddBatch) <= 100 ? Number(ddBatch) : 5\n const back = Math.round(Number.isFinite(Number(ddBack)) && Number(ddBack) >= 0 && Number(ddBack) <= 1440 ? Number(ddBack) : 15)\n const { error } = await supabase.from('organizations').update({\n doordash_nudge_enabled: ddNudge, doordash_max_miles: miles,\n doordash_wait_minutes: wait, doordash_avg_cost: cost, doordash_batch_radius_miles: batch,\n doordash_driver_back_minutes: back,\n }).eq('id', profile.org_id)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setDdMiles(String(miles)); setDdWait(String(wait)); setDdCost(String(cost)); setDdBatch(String(batch)); setDdBack(String(back))\n setMsg(ddNudge\n ? `DoorDash suggestions on — orders within ${miles} mi that have waited ${wait} min, with nothing within ${batch} mi to batch, at about $${cost}.`\n : 'DoorDash suggestions off.')\n reloadProfile?.() // the dispatch board reads these straight off the profile\n }\n\n async function savePtoRate() {\n const n = (v) => Math.max(0, Number(v) || 0)\n // Spread the stored object rather than rebuilding it. `full_time` is still a key in the DB on orgs that were\n // set up before the weekly model, and nothing here shows it — rebuilding would silently delete it on save.\n const byType = { ...ptoByTypeRaw, part_time: n(ptoPT), seasonal: n(ptoSeasonal) }\n const { error } = await supabase.from('organizations').update({ pto_accrual_by_type: byType, pto_accrual_rate: n(ptoDefault) }).eq('id', profile.org_id)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setMsg('PTO accrual rates saved.')\n }\n\n const toggleDispatcherPage = (key) => setDispatcherPages(prev => prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key])\n async function saveAccess() {\n const { error } = await supabase.from('organizations').update({ role_pages: { dispatcher: dispatcherPages } }).eq('id', profile.org_id)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setMsg('Page access saved. Dispatchers see the change next time they load a page.')\n }\n\n async function saveLocation(id) {\n const e = editLocations[id]\n if (!e) return\n // Same rule on edit as on create: a location cannot be saved with its starting address cleared. The column is NOT\n // NULL, so an empty string would save cleanly and leave the board with no depot at all.\n if (!(e.default_address || '').trim()) { setMsg('A location needs its own starting address — routes are measured from it.'); return }\n const addr = e.default_address.trim()\n // Re-place the depot on the map whenever the address changes. lat/lng used to be written by nothing at all, so\n // every location but org 703's had null coordinates — and delivery_time_by_distance() filters on\n // `depot.lat is not null`, which made the Delivery Time distance bands silently blank rather than wrong.\n // Best-effort: a geocode failure must not stop an admin correcting their address, so the address still saves and\n // the map placement is reported separately.\n // A CHANGED ADDRESS WITH NO NEW FIX MUST NOT KEEP THE OLD ONE. The address text and the coordinates describe the\n // same building or the row is lying: leaving lat/lng from the PREVIOUS address means the Delivery Time bands\n // measure from the old warehouse while the report names the new one — wrong, and invisible, because a stale\n // coordinate looks exactly like a good one. Clearing them makes the report say it is waiting on a depot address,\n // which is the same trade already made in \"don't trade a blank report for a confidently wrong one\".\n // Only when the address is UNCHANGED are the existing coordinates still a true description of it, so a transient\n // Google failure on an unrelated edit (renaming the location) never blanks a working report.\n const prev = locations.find(l => l.id === id)\n const addrChanged = (prev?.default_address || '').trim() !== addr\n const geo = await depotCoords(addr)\n const patch = { name: e.name, default_address: addr }\n if (geo.ok) { patch.lat = geo.lat; patch.lng = geo.lng }\n else if (addrChanged) { patch.lat = null; patch.lng = null }\n // The org_id filter is defence in depth, not the control: isolation rests on the locations RLS policy, and on\n // 2026-07-26 that policy was measured to be org-scoped but NOT role-tiered (a driver-role session could rewrite\n // this row -- see PROPOSED-locations-write-policy-split.sql). This filter does not close that hole, which is\n // intra-tenant; it costs nothing and means a mis-keyed id can never reach another tenant's row.\n const { error } = await supabase.from('locations').update(patch).eq('id', id).eq('org_id', profile.org_id)\n if (error) { setMsg(`Could not save: ${error.message}`); return }\n setMsg(geo.ok\n ? 'Location saved.'\n : addrChanged\n ? `Location saved, but the new address could not be placed on the map (${geo.error}). Its old coordinates were cleared rather than left pointing at the previous address, so the Delivery Time distance bands will say they are waiting on a depot address until this saves cleanly. Check the address is one Google recognises.`\n : `Location saved. The address could not be re-placed on the map (${geo.error}), but it did not change, so the Delivery Time distance bands carry on from where they already were.`)\n }\n\n async function addLocation() {\n if (!newLocName.trim()) return\n // The address is REQUIRED, and is never substituted. This line used to fall back to a hardcoded street address —\n // org 703's warehouse — so a location added without one quietly became \"Fenton, MO\" and every route from that\n // location was measured there. An unanswered question must stay unanswered; it must not be answered with somebody\n // else's depot.\n if (!newLocAddr.trim()) { setMsg('A location needs its own starting address — routes are measured from it.'); return }\n // The error was being discarded — a rejection (RLS, grant, or the not_null_violation the dropped default now\n // raises) cleared the form and closed the panel exactly like a success, so the admin walked away believing a\n // location existed that did not. saveLocation() directly above has always reported its error; this one didn't.\n const addr = newLocAddr.trim()\n const geo = await depotCoords(addr)\n const { error } = await supabase.from('locations').insert({\n org_id: profile.org_id,\n name: newLocName.trim(),\n default_address: addr,\n ...(geo.ok ? { lat: geo.lat, lng: geo.lng } : {}),\n })\n if (error) { setMsg(`Could not add that location: ${error.message}`); return }\n // The success path used to set no message at all, so a warning left over from a previous failed add sat on screen\n // above a location that had in fact saved cleanly — the reader cannot tell a stale message from a current one.\n setMsg(geo.ok\n ? 'Location added.'\n : `Location added, but the address could not be placed on the map (${geo.error}) — the Delivery Time distance bands need it.`)\n setNewLocName(''); setNewLocAddr(''); setShowAddLocation(false)\n const { data } = await supabase.from('locations').select('*').eq('org_id', profile.org_id)\n setLocations(data || [])\n const edits = {}\n for (const l of data || []) edits[l.id] = { name: l.name, default_address: l.default_address }\n setEditLocations(edits)\n }\n\n function updateLocEdit(id, field, value) {\n setEditLocations(prev => ({ ...prev, [id]: { ...prev[id], [field]: value } }))\n }\n\n // Persist the dispatch board layout for the whole org.\n async function saveLayout(next) {\n // Optimistic, and undone on a refusal — the same rule as saveOrg's revert below.\n const prev = layout\n setLayout(next); setLayoutSaved(false); setLayoutSaving(true)\n const { error } = await supabase.from('organizations').update({ board_layout: next }).eq('id', profile.org_id)\n setLayoutSaving(false)\n if (error) { setLayout(prev); saveFailed('The board layout', error); return }\n setLayoutSaved(true); reloadProfile?.(); setTimeout(() => setLayoutSaved(false), 2500)\n }\n\n // Persist the pre-seed toggle for the whole org.\n async function savePreseed(next) {\n const prev = preseed\n setPreseed(next); setPreseedSaved(false); setPreseedSaving(true)\n const { error } = await supabase.from('organizations').update({ preseed_enabled: next }).eq('id', profile.org_id)\n setPreseedSaving(false)\n if (error) { setPreseed(prev); saveFailed('Pre-seed routes', error); return }\n setPreseedSaved(true); reloadProfile?.(); setTimeout(() => setPreseedSaved(false), 2500)\n }\n\n // Persist customer tracking on/off + mode for the whole org.\n async function saveCustTrack(next) {\n const prev = custTrack\n setCustTrack(next); setCustSaved(false); setCustSaving(true)\n const { error } = await supabase.from('organizations').update({ customer_tracking_enabled: next }).eq('id', profile.org_id)\n setCustSaving(false)\n if (error) { setCustTrack(prev); saveFailed('Customer delivery tracking', error); return }\n setCustSaved(true); reloadProfile?.(); setTimeout(() => setCustSaved(false), 2500)\n }\n async function saveCustMode(next) {\n const prev = custMode\n setCustMode(next); setCustSaved(false); setCustSaving(true)\n const { error } = await supabase.from('organizations').update({ customer_tracking_mode: next }).eq('id', profile.org_id)\n setCustSaving(false)\n if (error) { setCustMode(prev); saveFailed('The tracking mode', error); return }\n setCustSaved(true); reloadProfile?.(); setTimeout(() => setCustSaved(false), 2500)\n }\n // STORED BLANK AS NULL, never as an empty string. NULL is what the fallback tests for, so clearing the box has to\n // mean \"go back to using our name\" — an empty string would satisfy a truthiness check somewhere downstream and leave\n // customers being texted by a business with no name at all.\n async function saveCustName() {\n const next = (custName || '').trim()\n setCustSaved(false); setCustSaving(true)\n const { error } = await supabase.from('organizations').update({ customer_facing_name: next || null }).eq('id', profile.org_id)\n setCustSaving(false)\n if (error) { saveFailed('The name customers see', error); return }\n setCustSaved(true); reloadProfile?.(); setTimeout(() => setCustSaved(false), 2500)\n }\n\n // NULL, never '' — the reminder treats a missing recipient as \"nobody has set one yet\" and holds the pickups rather\n // than sending into the void. An empty string would satisfy a truthiness check somewhere and become a send to \"\".\n async function savePickupEmail() {\n await saveOrg('pickupEmail', { pickup_email_to: (pickupEmail || '').trim() || null })\n }\n // Same NULL-never-'' rule. One address, validated before it is written: the reminder cron sends to exactly one.\n async function saveRenewalEmail() {\n const v = (renewalEmail || '').trim()\n if (v && !isEmailable(v)) {\n setRenewalErr(v.includes(',') ? 'One address only — use a group list if more than one person needs it.' : `“${v}” doesn't look like an email address.`)\n return\n }\n setRenewalErr(null)\n await saveOrg('renewalEmail', { registration_email_to: v || null })\n }\n function toggleReturns() { const n = !returnsOn; setReturnsOn(n); saveOrg('returns', { returns_enabled: n }, () => setReturnsOn(!n)) }\n\n // Generic org-column saver for the driver-capture + integration toggles. `key` drives the transient ✓ flash.\n // ON FAILURE IT MUST SAY SO. This saver stayed silent for every one of the thirty-odd settings it drives, and\n // `organizations` is a table where a perfectly ordinary new column is UNWRITABLE until somebody adds it to the\n // write allowlist — so \"refused\" is a routine outcome here, not an exotic one. Silence turned that into a\n // setting that reads as saved, flashes nothing, and is gone on the next reload.\n //\n // AND THE SWITCH GOES BACK (2026-10-26). The toggles flip their state BEFORE calling this, so the click feels\n // instant — and on a refusal the message said \"NOT saved\" while the switch beside it stayed flipped, showing the\n // very state the database had just refused. `revert` is the toggle's own undo, run on failure. `.select('id')` so\n // an RLS refusal (zero rows matched — View As, read-only) counts as a failure too; it does not error. Returns\n // whether the change was stored.\n async function saveOrg(key, patch, revert) {\n setFeatSaved(null)\n const { data, error } = await supabase.from('organizations').update(patch).eq('id', profile.org_id).select('id')\n if (error || !data?.length) {\n revert?.()\n saveFailed(ORG_SETTING_LABELS[key] || 'That setting', error || { message: 'the change did not apply (read-only view, or no permission)' })\n return false\n }\n setFeatSaved(key); reloadProfile?.(); setTimeout(() => setFeatSaved((k) => (k === key ? null : k)), 2500)\n return true\n }\n function toggleAddrCapture() { const n = !addrCapture; setAddrCapture(n); saveOrg('addrCapture', { address_capture_enabled: n }, () => setAddrCapture(!n)) }\n function toggleSavedAddr() { const n = !savedAddr; setSavedAddr(n); saveOrg('savedAddr', { saved_addresses_enabled: n }, () => setSavedAddr(!n)) }\n function togglePod() { const n = !pod; setPod(n); saveOrg('pod', { pod_enabled: n }, () => setPod(!n)) }\n function toggleBarcode() { const n = !barcode; setBarcode(n); saveOrg('barcode', { barcode_enabled: n }, () => setBarcode(!n)) }\n function toggleWinback() { const n = !winbackEn; setWinbackEn(n); saveOrg('winback', { winback_enabled: n }, () => setWinbackEn(!n)) }\n function toggleChecklist() { const n = !checklistEn; setChecklistEn(n); saveOrg('checklist', { checklist_enabled: n }, () => setChecklistEn(!n)) }\n function toggleRemind() { const n = !remindEn; setRemindEn(n); saveOrg('checklistremind', { checklist_remind_enabled: n }, () => setRemindEn(!n)) }\n function saveRemind() { saveOrg('remindcfg', { checklist_remind_time: remindTime, checklist_remind_message: remindMsg.trim() || null }) }\n function toggleCod() { const n = !cod; setCod(n); saveOrg('cod', { cod_enabled: n }, () => setCod(!n)) }\n function toggleExceptions() { const n = !exceptions; setExceptions(n); saveOrg('exceptions', { exceptions_enabled: n }, () => setExceptions(!n)) }\n function toggleAfterhours() { const n = !ahEnabled; setAhEnabled(n); saveOrg('afterhours', { afterhours_alert_enabled: n }, () => setAhEnabled(!n)) }\n function saveAfterhours() {\n let tz = null; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone } catch { /* older browsers */ }\n saveOrg('afterhoursCfg', {\n afterhours_alert_phone: ahPhone.trim() || null,\n afterhours_open: ahOpen || '07:00',\n afterhours_close: ahClose || '18:00',\n afterhours_days: ahDays,\n afterhours_threshold_m: Math.max(50, Number(ahThreshold) || 300),\n afterhours_tz: tz, // so the UTC cron can judge this location's local \"after-hours\"\n })\n }\n // Shift-only tracking — turning the fleet-wide default window on/off, and saving its hours. Both stamp the browser's tz\n // so the UTC cron judges \"in shift\" in the org's local time (same trick as after-hours). Per-vehicle windows override\n // this on the Vehicles screen.\n function toggleFleetShift() {\n const n = !fleetShiftDefault; setFleetShiftDefault(n)\n let tz = null; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone } catch { /* older browsers */ }\n saveOrg('fleetShift', { fleet_shift_default: n, fleet_shift_tz: tz }, () => setFleetShiftDefault(!n))\n }\n function saveShiftWindow() {\n let tz = null; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone } catch { /* older browsers */ }\n saveOrg('shiftCfg', {\n fleet_shift_open: shiftOpen || '07:00',\n fleet_shift_close: shiftClose || '18:00',\n fleet_shift_days: shiftDays,\n fleet_shift_tz: tz,\n })\n }\n // POSITION-HISTORY RETENTION. Clamped to the same 1..365 the database constraint enforces, and clamped BEFORE\n // the write rather than after the error, because the failure this avoids is destructive in one direction only:\n // a typo'd 0 or 3 does not raise anything a user would understand, it just silently shortens how much of their\n // own history survives tonight. The DB constraint is the real floor; this is so nobody has to hit it.\n function savePingRetention() {\n const n = parseInt(pingKeepDays, 10)\n const days = Number.isFinite(n) ? Math.min(365, Math.max(1, n)) : 30\n setPingKeepDays(String(days))\n saveOrg('pingKeep', { ping_retention_days: days })\n }\n async function sendAfterhoursTest() {\n setAhTest('sending')\n // TEST THE ON-SCREEN NUMBER — which means it has to be SAVED first: the test texts whatever the org row holds. This\n // write used to be discarded, so a refused save (RLS matches no rows, it does not error) texted the OLD number and\n // the screen still said \"Test text sent\" beside the new one. Stop instead.\n const { data: saved, error: saveErr } = await supabase.from('organizations')\n .update({ afterhours_alert_phone: ahPhone.trim() || null }).eq('id', profile.org_id).select('id')\n if (saveErr || !saved?.length) { setAhTest(`Couldn’t save the number, so no test was sent: ${saveErr?.message || 'you may not have permission'}`); return }\n const { data, error } = await supabase.functions.invoke('afterhours-watch', { body: { action: 'test' } })\n if (error || data?.error) setAhTest(data?.error || error?.message || 'Could not send test')\n else { setAhTest('sent'); setTimeout(() => setAhTest(null), 5000) }\n }\n function toggleCustomers() { const n = !customersEn; setCustomersEn(n); saveOrg('customers', { customers_enabled: n }, () => setCustomersEn(!n)); reloadProfile?.() }\n function toggleRecurring() { const n = !recurringEn; setRecurringEn(n); saveOrg('recurring', { recurring_enabled: n }, () => setRecurringEn(!n)); reloadProfile?.() }\n function toggleCapacityRouting() { const n = !capacityRouting; setCapacityRouting(n); saveOrg('capacity', { capacity_routing_enabled: n }, () => setCapacityRouting(!n)) }\n function togglePodEmail() { const n = !podEmailEn; setPodEmailEn(n); saveOrg('podEmail', { pod_email_enabled: n }, () => setPodEmailEn(!n)) }\n function toggleRatings() { const n = !ratingsEn; setRatingsEn(n); saveOrg('ratings', { ratings_enabled: n }, () => setRatingsEn(!n)) }\n function toggleWhitelabel() { const n = !whitelabel; setWhitelabel(n); saveOrg('whitelabel', { whitelabel_enabled: n }, () => setWhitelabel(!n)) }\n function saveLogo() { saveOrg('logo', { logo_url: logoUrl.trim() || null }) }\n // Customer image library (Settings → Images). Loaded on mount, org-scoped in storage.\n useEffect(() => { if (profile?.org_id) listOrgImages(profile.org_id).then(setOrgImages) }, [profile?.org_id])\n\n // Clock network settings come from an RPC, not the organizations row, so they load separately.\n useEffect(() => {\n if (!profile?.org_id) return\n getClockIpSettings().then(({ enabled, ips, kioskCode, error }) => {\n if (error) return // non-admin or RPC missing — leave the safe default (restriction on)\n setClockIpOn(enabled); setClockIps(ips); setKioskCode(kioskCode)\n })\n }, [profile?.org_id])\n async function onUploadImage(e) {\n const file = e.target.files?.[0]; if (e.target) e.target.value = ''\n if (!file) return\n setImgBusy(true)\n const { error } = await uploadOrgImage(profile?.org_id, file)\n if (error) alert('Upload failed: ' + error)\n else setOrgImages(await listOrgImages(profile?.org_id))\n setImgBusy(false)\n }\n async function onDeleteImage(path) {\n if (!window.confirm('Delete this image?')) return\n await deleteOrgImage(path)\n setOrgImages(await listOrgImages(profile?.org_id))\n }\n // Whitelabel logo — uploaded through the image library (lands in org-media) and set as logo_url in one step.\n async function onUploadLogo(e) {\n const file = e.target.files?.[0]; if (e.target) e.target.value = ''\n if (!file) return\n setImgBusy(true)\n const { url, error } = await uploadOrgImage(profile?.org_id, file)\n if (error) alert('Upload failed: ' + error)\n else { setLogoUrl(url); saveOrg('logo', { logo_url: url }); setOrgImages(await listOrgImages(profile?.org_id)) }\n setImgBusy(false)\n }\n function saveAlertMessages() { saveOrg('alertmsgs', { idle_alert_message: idleMsg.trim() || null, lost_alert_message: lostMsg.trim() || null, stationary_alert_message: stationaryMsg.trim() || null }) }\n function toggleDriverPay() { const n = !driverPay; setDriverPay(n); saveOrg('driverpay', { driver_pay_enabled: n }, () => setDriverPay(!n)) }\n function savePayRates() { saveOrg('payrates', { pay_per_stop: payPerStop === '' ? null : Number(payPerStop), pay_per_mile: payPerMile === '' ? null : Number(payPerMile) }) }\n // MINTED BY THE SERVER, NOT HERE (2026-10-26). Both secrets used to be generated in the browser — crypto.randomUUID,\n // or Math.random where that was missing — and written with a plain UPDATE that any member holding the column grant\n // could have made. The columns are no longer writable from the browser; ensure_org_integration_secret mints one if\n // absent (admin/owner only) and returns it, and an existing secret is kept, exactly as before. The switch is saved\n // only once the secret exists, so \"on\" can never be stored without something to sign or authenticate with.\n async function ensureSecret(kind, label) {\n const { data, error } = await supabase.rpc('ensure_org_integration_secret', { p_kind: kind })\n if (error || !data) { saveFailed(label, error); return null }\n return data\n }\n async function toggleWebhooks() {\n const n = !webhooks; setWebhooks(n)\n if (n && !webhookSecret) {\n const secret = await ensureSecret('webhook_secret', 'The webhook signing secret')\n if (!secret) { setWebhooks(!n); return }\n setWebhookSecret(secret)\n }\n saveOrg('webhooks', { webhooks_enabled: n }, () => setWebhooks(!n))\n }\n function saveWebhookUrl() { saveOrg('webhookUrl', { webhook_url: webhookUrl.trim() || null }) }\n function toggleBilling() { const n = !billingEnabled; setBillingEnabled(n); saveOrg('billing', { billing_enabled: n }, () => setBillingEnabled(!n)) }\n async function toggleApi() {\n const n = !apiEnabled; setApiEnabled(n)\n if (n && !apiKey) {\n const key = await ensureSecret('api_key', 'The API key')\n if (!key) { setApiEnabled(!n); return }\n setApiKey(key)\n }\n saveOrg('api', { api_enabled: n }, () => setApiEnabled(!n))\n }\n\n function pick(c) { setColor(c); applyAccent(c); setSaved(false) } // live preview as the user picks\n async function saveColor() {\n setSaving(true)\n const { error } = await supabase.from('organizations').update({ theme_color: color }).eq('id', profile.org_id)\n setSaving(false)\n // `pick` already repainted the whole app with this accent, so a refused save leaves the brand colour looking\n // changed everywhere while the stored one is untouched — the most visibly wrong of the silent failures.\n if (error) { saveFailed('The brand colour', error); return }\n setSaved(true); reloadProfile?.(); setTimeout(() => setSaved(false), 2500)\n }\n\n if (profile?.role !== 'admin') {\n return
Site Settings are only available to admins.
\n }\n\n return (\n
\n

Site Settings

\n

Organization-wide settings for your whole team.

\n\n {msg && (\n
{msg}
\n )}\n\n {/* Sticky section nav — same pill language as Trip History's segmented control. Tab-style: each chip swaps the\n visible section rather than scrolling to it. */}\n
\n {SECTIONS.map(s => (\n \n ))}\n
\n\n {section === 'company' && <>\n {/* Organization name */}\n
\n

Organization

\n \n
\n setOrgName(e.target.value)} />\n \n
\n\n {/* Show/hide the manual \"Add an Address\" capture box on the dispatch board (whole org). */}\n
\n \n
\n
Show “Add an Address” on dispatch
\n

The manual address-entry box on the dispatch board — Google address lookup plus bulk paste / file import. Turn off if your team never types delivery addresses by hand (e.g. PhotoScan-only shops) to keep the board clear. The scan button and the saved list stay put either way.

\n
\n {featSaved === 'addrCapture' && ✓ Saved}\n
\n\n {/* Show/hide the Saved Addresses card on the dispatch board (whole org). Independent of the toggle above. */}\n
\n \n
\n
Show “Saved addresses”
\n

Your org’s address book, on the board just below “Scan the invoice.” Every address you dispatch is saved here automatically. Use Manage on the card to pin the ones you deliver to most — pinned addresses stay at the top, in the order you drag them.

\n
\n {featSaved === 'savedAddr' && ✓ Saved}\n
\n
\n }\n\n {section === 'routing' && <>\n {/* Routing — handling time + the route time cap (the \"1Hr\" cap, now any value) */}\n
\n

Routing

\n\n \n
\n setStopMinutes(e.target.value)} />\n
\n

Added at each stop (handling time) on top of drive times, in every per-stop ETA and the route total.

\n\n \n
\n setCapMinutes(e.target.value)} />\n
\n

The cap used by the per-driver toggle on the board (shown as “{capLabel(capMinutes)}”). When a driver is capped, Auto-assign trims their route to get back to base within this window (±10 min). Default 60.

\n\n \n
\n setIdleMinutes(e.target.value)} />\n \n
\n

If a driver's vehicle sits this long away from any stop while out on a run (during business hours), the board pops an idle alert and the driver is automatically texted to check in. Time parked at a delivery, pickup, or fuel stop doesn't count. Default 12.

\n\n \n
\n setStationaryMinutes(e.target.value)} />\n \n
\n

If a driver's vehicle doesn't move this long anywhere on the route — at a stop, between stops, or on the way back — the board raises a “check they're OK” alert and the driver is auto-texted to ask if they're all right. Unlike the idle alert, time parked at a delivery does count: the question is whether they're OK, not whether they're working. Runs until 6pm rather than 5pm. Default 30.

\n\n \n
\n setLostMinutes(e.target.value)} />\n \n
\n

If a driver falls this many minutes behind the estimated time to reach their next stop (while still en route), the board raises a loud “may be lost” alert and the driver is auto-texted to call dispatch. This is now the primary live interrupt (off-route is a passive card indicator). Default 20.

\n\n \n
\n setReviewMinutes(e.target.value)} />\n \n
\n

A finished route that ran this many minutes past its plan lands in Routes to review on Trip History, where an admin opens it and marks it reviewed. Measured on driver-accountable time, so fuel stops and long customer holds are already taken out. Lower it to see more routes; routes you have already cleared never come back. Default 20.

\n
\n\n {/* DoorDash suggestions — advice about spending money, so it is its own section with its own Save. */}\n
\n

DoorDash suggestions

\n \n

\n When an unassigned delivery is close, has been sitting, and has\n nothing nearby to be batched with, the board suggests sending it by courier and shows\n the cost. It is only ever a suggestion — nothing is sent automatically. Turn this on when you would\n rather pay a courier than tie a vehicle up on a one-delivery round trip. Off by default.\n

\n\n
\n
\n \n setDdMiles(e.target.value)} />\n

Past this distance the suggestion stays quiet. Keep it inside the range you actually have courier pricing for — a quote you have never tested is a guess.

\n
\n
\n \n setDdWait(e.target.value)} />\n

Normally 0. Once the other conditions hold we already know no vehicle is coming for this order, so making it sit first just re-creates the delay this is meant to remove. Raise it only if you want a beat before the board speaks up.

\n
\n
\n \n setDdBatch(e.target.value)} />\n

If another waiting delivery sits within this distance, the two can ride together and no suggestion appears. This is what stops you paying a courier for a stop that was about to share a vehicle anyway — the single most important number here. A backtest over one week fired 29 times at 5 miles but only 7 of those really needed a dedicated vehicle; at 10 miles it fired 10 times. Raise it if suggestions turn out to be for stops a route absorbed anyway.

\n
\n
\n \n setDdBack(e.target.value)} />\n

If a driver is idle at the shop, or a run is due back inside this window, no suggestion appears — the vehicle can take it. This is what stops you paying a courier for an order a returning driver was about to collect.

\n
\n
\n \n setDdCost(e.target.value)} />\n

Used for measuring what the programme costs against the vehicle-hours it frees. Deliberately not shown to the dispatcher — whether couriers are worth it is decided here, once, not re-argued on every order.

\n
\n
\n\n
\n
\n }\n\n {section === 'timeclock' && <>\n {/* Kiosk link — the company's own address for the shared clock screen. /time is one front door for every\n company, so before anyone signs in this code is how it knows whose names to show (2026-10-12). */}\n {kioskCode && (\n
\n

Time clock link

\n

\n Open this on the shop computer, or send it to your drivers to bookmark. It shows only your people.\n

\n
\n e.target.select()} />\n \n
\n
\n )}\n\n {/* Time clock — network restriction */}\n
\n

Time clock & PIN sign-in — network

\n \n {/* The heading and copy name PIN sign-in explicitly because this switch governs BOTH. It always intended to —\n the login screen simply never read it until 2026-07-20 — and a switch labelled \"time clock\" that also\n decides who can sign in is the kind of surprise that gets flipped for one reason and breaks the other. */}\n

\n On, people can only punch — and only sign in with a PIN — from an address listed below, so nobody clocks in\n from home. Off, anyone with a PIN can do both from anywhere. Leave it on unless your team works somewhere\n without a fixed internet address. To let one person work off-site without opening it up for everyone, tick\n Clock in and sign in from anywhere on that person instead.\n

\n\n {clockIpOn && (\n
\n \n
\n setClockIps(e.target.value)} placeholder=\"162.192.100.129\" />\n {/* Nobody knows their own public IP, and guessing it wrong locks the whole shop out of the clock. */}\n \n
\n

\n Separate several with commas. This is the building's public internet address, not a computer's local one —\n if the shop's internet provider changes it, clocking in stops working until it's updated here.\n

\n
\n )}\n\n

\n Someone who genuinely needs to punch from elsewhere can be given Clock in from anywhere on\n their own record, instead of turning this off for everybody.\n

\n\n
\n \n {clockIpMsg && {clockIpMsg}}\n
\n
\n\n {/* Payroll / PTO — payroll access only. Holds the pay-period cadence, PTO accrual rates and the delivery-based\n driver pay rates, i.e. what people are paid; a manager without payroll access never sees this section. */}\n {canViewPayroll(profile) && (\n
\n

Payroll

\n {/* NO FULL-TIME BOX HERE, AND THAT IS THE POINT. Full-time accrues a flat number of hours per whole week\n (tiered at the tenure mark) and `accruedFor()` never reads an hourly rate for them — so the Full-time\n input this grid used to carry set a number nothing read, on a screen that told the admin it was applied.\n Its numbers live on the Payroll screen's \"Accrual rates\" card, which is the surface that owns them. */}\n \n
\n Part-time\n setPtoPT(e.target.value)} />\n Seasonal\n setPtoSeasonal(e.target.value)} />\n Default (no type)\n setPtoDefault(e.target.value)} />\n
\n
\n

Set each employee's type on their profile in User Management. These rates earn PTO by the hour: their portal shows accrued = hours worked × their type's rate, on top of any starting balance carried in. e.g. 0.0333 ≈ 1 hour of PTO per 30 worked; 0 turns accrual off. People with no type use the Default rate. Full-time is a different model — a flat number of hours per week, more after the tenure mark — and is set on the Payroll screen under Accrual rates, along with the tenure mark itself.

\n
\n )}\n }\n\n {section === 'integrations' && <>\n {/* Access — pages by role */}\n
\n

Access — pages by role

\n

Managers and owners always have every page. Choose which pages a Dispatcher can open — anything unchecked is hidden from their nav and blocked if they try the URL. (Drivers use their own portal.)

\n
\n {PAGES.map(p => (\n \n ))}\n
\n
\n
\n }\n\n {section === 'company' && <>\n {/* Locations */}\n
\n

Locations

\n {locations.map(loc => (\n
\n \n updateLocEdit(loc.id, 'name', e.target.value)} />\n \n updateLocEdit(loc.id, 'default_address', e.target.value)} />\n \n
\n ))}\n {showAddLocation ? (\n
\n \n setNewLocName(e.target.value)} placeholder=\"Main Warehouse\" />\n \n setNewLocAddr(e.target.value)} placeholder=\"123 Main St, City ST 00000\" />\n
\n \n \n
\n
\n ) : (\n \n )}\n
\n }\n\n {section === 'routing' && <>\n {/* Dispatch board layout */}\n
\n

Dispatch board layout

\n

\n 2-Up keeps the address card open on the left (best when you're entering addresses all day). 3-Up collapses the address into a drop-down and moves team chat to the header, so the board shows three driver cards across. 4-Up is like 3-Up but with four driver cards across — extra screen real estate for busier shops running more drivers.\n

\n
\n {[\n { key: '2up', title: '2-Up Layout', desc: 'Address card always open · 2 driver cards across', art: '▣ ▏ ▣ ▣' },\n { key: '3up', title: '3-Up Layout', desc: 'Address collapses · chat in header · 3 cards across', art: '▏ ▣ ▣ ▣' },\n { key: '4up', title: '4-Up Layout', desc: 'Address collapses · chat in header · 4 cards across (busy shops)', art: '▏ ▣ ▣ ▣ ▣' },\n ].map((opt) => {\n const sel = layout === opt.key\n return (\n \n )\n })}\n
\n {layoutSaved &&
✓ Saved for your team
}\n
\n\n {/* Pre-seed routes */}\n
\n

Pre-seed routes

\n

\n When this is on, dragging an unassigned address onto a driver's card before you press Auto-assign “pre-seeds” that driver: it pins them to that area, and Auto-assign builds their route around it, pulling in the nearby stops. The rest of the board is split among the remaining drivers as usual. Use it when you want a particular driver to take a particular part of town. When it's off, Auto-assign ignores any manual drops and clusters every stop from scratch. Default: off.\n

\n
\n \n {preseed ? 'On' : 'Off'}\n {preseedSaved && ✓ Saved for your team}\n
\n
\n }\n\n {section === 'customers' && <>\n {/* Customer delivery tracking */}\n
\n

Customer delivery tracking

\n

\n Text your customers a live tracking link with a real-time ETA — they see where their delivery is and how many stops away the driver is. Off by default. A customer is only texted if a phone number is on their stop; when you dispatch, you'll be prompted to add any that are missing (you can skip a stop by leaving it blank).\n

\n
\n \n {custTrack ? 'On' : 'Off'}\n {custSaved && ✓ Saved for your team}\n
\n\n {/* THE NAME CUSTOMERS KNOW YOU BY, which is not always the name on the account. An org record's name is often an\n internal designation — a branch code, a location number — and until this existed that code was what every\n automatic text signed off with, to people who had never heard it. Sits ABOVE the mode picker because it\n applies to whichever mode is chosen, and because the wrong name on the right number is the worse failure. */}\n {custTrack && (\n
\n \n setCustName(e.target.value)}\n onBlur={saveCustName}\n disabled={custSaving}\n maxLength={80}\n placeholder={profile?.organizations?.name || 'Your business name'}\n style={{ width: '100%', boxSizing: 'border-box', background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: '8px', color: 'var(--text)', fontSize: '15px', padding: '0.55rem 0.7rem', fontFamily: 'inherit' }}\n />\n

\n Used only where a customer sees it — the delivery texts and the tracking page. Your dispatch board, reports\n and admin screens keep showing {profile?.organizations?.name || 'your account name'}.\n Leave it blank to use that everywhere.\n

\n
\n )}\n\n {custTrack && (\n
\n {[\n { key: 'single', title: 'Single text', desc: 'One message — the “you’re next / on the way” alert with a live link, sent when the driver leaves the previous stop. Lowest cost (~1 text per delivery).' },\n { key: 'multi', title: 'Full updates', desc: 'A tracking link when the order goes out, an “almost there / you’re next” alert, and a “delivered” confirmation. The full experience (~2–3 texts per delivery).' },\n ].map((opt) => {\n const sel = custMode === opt.key\n return (\n \n )\n })}\n
\n )}\n
\n }\n\n {section === 'drivers' && <>\n {/* Proof of delivery */}\n
\n

Proof of delivery

\n

\n When on, the driver is asked to capture proof at each stop before marking it done — a photo, a signature, and an optional recipient name. The proof is saved with the stop and shown in Trip History (and on the customer's tracking page). Off by default — turn it on when your drivers are ready to use it.\n

\n
\n \n {pod ? 'On' : 'Off'}\n {featSaved === 'pod' && ✓ Saved for your team}\n
\n
\n\n {/* Barcode / QR scanning */}\n
\n

Barcode / QR scanning

\n

\n When on, the driver can scan a package barcode or QR code at each stop (phone camera) to confirm the right item was delivered. The scanned value is saved with the stop. Off by default. Works best on Android/Chrome; iPhones fall back to manual entry.\n

\n
\n \n {barcode ? 'On' : 'Off'}\n {featSaved === 'barcode' && ✓ Saved for your team}\n
\n
\n\n {/* Cash on delivery (COD) */}\n
\n

Cash on delivery (COD)

\n

\n When on, the dispatcher can mark any unassigned order COD (with the 💵 button on the stop) and enter the amount due. At that stop the driver sees the amount and closes it as paid only by confirming he took the money himself — nothing else on his screen can mark cash collected. If he can't collect it, he is never left stranded: he can record “delivered, collecting payment later” with a note, and the trip shows the amount NOT COLLECTED for whoever chases it. Off by default.\n

\n
\n \n {cod ? 'On' : 'Off'}\n {featSaved === 'cod' && ✓ Saved for your team}\n
\n
\n\n {/* Returns (RMA). The ↩ button had been on every unassigned stop for every org while this column sat unread;\n measured 2026-10-21, no org had ever marked a return, so gating it took nothing from anyone.\n 2026-10-28: a return is a DELIVERY that also brings something back (captureRules isDeliveryPlusReturn) — this\n copy said \"collects goods back instead of dropping off\" and \"↩ RETURN\", both of which the d035da08 change made\n untrue. ↩ is offered on deliveries only (StopChip). */}\n
\n

Returns

\n

\n When on, the dispatcher can add a return to an unassigned delivery (the ↩ button on the stop) — the\n driver delivers the order as usual, then photographs the return the customer hands him and brings it back. The\n stop shows ↩ + RETURN on the board and on the driver's route, and the return photo sits beside the\n proof of delivery on the board and in Trip History. Turning it off hides the button on new stops; a stop\n already marked keeps its label and can still be cleared. Off by default.\n

\n
\n \n {returnsOn ? 'On' : 'Off'}\n {featSaved === 'returns' && ✓ Saved for your team}\n
\n
\n\n {/* Failed-delivery exceptions */}\n
\n

Failed-delivery exceptions

\n

\n When on, a driver who can't complete a stop gets a “Couldn't deliver” button to log the reason (nobody home / shop closed, refused, bad address, no access, damaged, other) + a note. The exception is recorded in Trip History and sent on the stop.failed webhook. Off by default.\n

\n
\n \n {exceptions ? 'On' : 'Off'}\n {featSaved === 'exceptions' && ✓ Saved for your team}\n
\n
\n }\n\n {section === 'alerts' && <>\n {/* After-hours vehicle movement alert */}\n
\n

After-hours movement alert

\n

\n For locations with a yard full of vehicles: when on, Route Now watches your GPS vehicles outside the hours you\n set below. If a vehicle moves more than the threshold — so ordinary GPS jitter is ignored — while you're closed,\n it texts the number below and drops a banner on the Dispatch board naming the vehicle(s), so\n whoever opens up next sees it. Off by default.\n

\n
\n \n {ahEnabled ? 'On' : 'Off'}\n {featSaved === 'afterhours' && ✓ Saved for your team}\n
\n\n \n setAhPhone(e.target.value)} />\n\n
\n
setAhOpen(e.target.value)} />
\n
setAhClose(e.target.value)} />
\n
setAhThreshold(e.target.value)} />
\n
\n\n \n
\n {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((d, idx) => {\n const on = ahDays.includes(idx)\n return (\n \n )\n })}\n
\n\n
\n \n \n {featSaved === 'afterhoursCfg' && ✓ Saved}\n {ahTest === 'sent' && ✓ Test text sent}\n {ahTest && ahTest !== 'sending' && ahTest !== 'sent' && {ahTest}}\n
\n
\n\n {/* NOT-READY PICKUP REMINDERS. Its own section rather than a line in the after-hours card above: that one is a\n movement alert about vehicles and this is a to-do list about customers, and the two share only the fact that\n both send a message. A setting filed under the wrong heading is a setting nobody finds. */}\n
\n

Pickup reminders

\n

\n When a pickup is marked not ready on the board, it carries a date to ring the customer back.\n The morning that date arrives we email this address — one message, subject “pickups”, listing\n each shop with its address and phone number so somebody can call without opening the app.\n

\n\n \n setPickupEmail(e.target.value)} />\n\n
\n \n {featSaved === 'pickupEmail' && ✓ Saved}\n
\n {/* SAYS IT CANNOT SEND YET, rather than looking configured and going quiet. Route Now has no email provider —\n every other notification it sends is a text — so until the key is in place this setting is armed and\n inert, and a screen that hid that would have somebody trusting a reminder that never arrives. */}\n

\n ⚠ The sending mailbox is not connected yet. Pickups still hold and still show their date on the board — but no\n email leaves the building until it is. Nothing is lost in the meantime: the moment it is connected, every\n pickup still waiting is included in that morning’s message.\n

\n
\n\n {/* RENEWAL REMINDERS (Brian, 2026-10-21). `registration_email_to` drove the plates + insurance reminder cron\n (registration-remind) from day one but could only be set in the database. ONE address: the cron sends to\n exactly one recipient, so a comma list is refused here rather than accepted and silently never delivered. */}\n
\n

Renewal reminders

\n

\n This address receives insurance and registration renewal reminders for your delivery\n vehicles — one email when a policy or plate sticker is coming up for renewal (or has already lapsed). Dates\n come from each vehicle on the Vehicles page. Leave it blank and no reminder is sent.\n

\n \n { setRenewalEmail(e.target.value); setRenewalErr(null) }} />\n {renewalErr &&

{renewalErr}

}\n
\n \n {featSaved === 'renewalEmail' && ✓ Saved for your team}\n
\n
\n\n {/* Shift-only tracking — only shown to orgs we've enabled it for (shift_tracking_enabled master flag). */}\n {shiftTrackOn && (\n
\n

Shift-only tracking

\n

\n For company trackers in a driver's personal vehicle: Route Now watches a vehicle only\n during the shift window below. Outside it — evenings, weekends, days off — Route Now ingests, stores\n and shows nothing: no live position, no history, no alerts. Set a fleet-wide default here;\n override it for an individual vehicle on the Vehicles screen. Off by default.\n

\n
\n \n {fleetShiftDefault ? 'On — fleet default window active' : 'Off'}\n {featSaved === 'fleetShift' && ✓ Saved for your team}\n
\n\n
\n
setShiftOpen(e.target.value)} />
\n
setShiftClose(e.target.value)} />
\n
\n\n \n
\n {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((d, idx) => {\n const on = shiftDays.includes(idx)\n return (\n \n )\n })}\n
\n\n
\n \n {featSaved === 'shiftCfg' && ✓ Saved}\n
\n
\n )}\n\n {/* Position history retention. Sits next to shift-only tracking because it answers the same question a driver\n asks — how much of where I have been does the company hold — just on the time axis instead of the clock. */}\n
\n

Position history

\n

\n How long to keep the trail of where your drivers have been — both the positions reported by their phones and,\n where fitted, by vehicle trackers. Anything older is deleted automatically each night. Keeping\n less is the privacy-friendlier choice and the cheaper one; keeping more means a delivery dispute months old can\n still be answered. This does not affect trip history, delivery times or reporting — those are\n stored separately and are not touched by this.\n

\n
\n setPingKeepDays(e.target.value)} />\n days\n \n {featSaved === 'pingKeep' && ✓ Saved}\n
\n

Between 1 and 365 days. Default 30.

\n
\n }\n\n {section === 'customers' && <>\n {/* Customer directory */}\n
\n

Customer directory

\n

\n When on, a Customers page appears under Manage — a directory of your regular accounts (shops/dealers) with saved contacts, account codes, default COD, and notes. Off by default.\n

\n
\n \n {customersEn ? 'On' : 'Off'}\n {featSaved === 'customers' && ✓ Saved for your team}\n
\n
\n\n {/* Recurring orders */}\n
\n

Recurring orders

\n

\n When on, a Recurring orders page appears under Manage where you set up standing deliveries (daily or specific weekdays). Each scheduled day, those orders drop onto the dispatch board automatically. Off by default.\n

\n
\n \n {recurringEn ? 'On' : 'Off'}\n {featSaved === 'recurring' && ✓ Saved for your team}\n
\n
\n }\n\n {section === 'routing' && <>\n {/* Capacity- & time-window-aware auto-assign */}\n
\n

Capacity & time-window routing

\n

\n When on, Auto-assign respects each vehicle's load capacity (set per vehicle on the Vehicles page) — it won't pile more weight/units on a van than it holds, pushing overflow back to Unassigned — and holds orders whose delivery window hasn't opened yet (orders with a future \"deliver after\" time). Off by default.\n

\n
\n \n {capacityRouting ? 'On' : 'Off'}\n {featSaved === 'capacity' && ✓ Saved for your team}\n
\n
\n\n {/* Marketing visits (light CRM) — Plan visits, visit outcomes, flyers, Visits history and the win-back campaign list. Customer-switchable, off by default. */}\n
\n

Marketing visits

\n

\n For field reps and drivers who call on accounts. When on, the dispatch board gets 🏷 Plan visits (add the accounts due for a visit) and an Add as marketing visits option on Import file, and each driver card shows a 🏷 Win back button listing campaign shops within 2 miles of that route. At each visit the rep records how it went, sets a follow-up date and notes which flyer they left. Every visit is kept on the customer's Visits history. Visits never count as deliveries. Off by default.\n

\n
\n \n {winbackEn ? 'On' : 'Off'}\n {featSaved === 'winback' && ✓ Saved for your team}\n
\n {/* The flyers the reps leave (2026-10-20) — only while marketing visits are on, like every other piece of them. */}\n {winbackEn && }\n
\n }\n\n {section === 'customers' && <>\n {/* Delivered-with-proof email to the shop — hidden until Route Now switches the feature on (src/lib/features.js). */}\n {FEATURES.podEmail &&
\n

Delivery confirmation emails

\n

\n When on, each shop gets an email the moment its delivery is completed — “Delivered at 10:42 AM, received by Mike” — with the proof photo and signature (links last 7 days). It goes to the delivery email saved on the customer, and you can switch any one shop off on the Customers page. Pickups and returns are never emailed. Off by default.\n

\n
\n \n {podEmailEn ? 'On' : 'Off'}\n {featSaved === 'podEmail' && ✓ Saved for your team}\n
\n {/* SAID WHEN IT CANNOT SEND. The switch stays usable so the choice is ready, but an On that sends nothing\n because email is not enabled for the account would be a setting that silently does nothing. */}\n {podEmailEn && emailEntitled === false && (\n

\n Email sending is not enabled on your account yet, so no emails will go out until Route Now switches it on.\n

\n )}\n
}\n\n {/* Delivery ratings */}\n
\n

Delivery ratings

\n

\n When on, after a delivery the customer's tracking page shows a quick 1–5 star rating + optional comment. Ratings collect against the order so you can see how each delivery landed. Requires Customer delivery tracking to be on. Off by default.\n

\n
\n \n {ratingsEn ? 'On' : 'Off'}\n {featSaved === 'ratings' && ✓ Saved for your team}\n
\n
\n\n {/* White-label tracking */}\n
\n

White-label customer tracking

\n

\n When on, the customer tracking page shows your logo and brand color and drops the \"Powered by Route Now\" footer — so the tracking experience looks like yours. Off by default.\n

\n
\n \n {whitelabel ? 'On' : 'Off'}\n {featSaved === 'whitelabel' && ✓ Saved for your team}\n
\n {whitelabel && (\n <>\n \n
\n \n {imgBusy && Uploading…}\n {logoUrl && \"logo\"}\n
\n

Upload your logo (it's saved to your image library below) — or paste a URL:

\n
\n setLogoUrl(e.target.value)} placeholder=\"https://your-site.com/logo.png\" />\n \n
\n {featSaved === 'logo' &&
✓ Saved
}\n \n )}\n
\n }\n\n {section === 'company' && <>\n {/* Images — feature-screenshot gallery + the customer's own image library */}\n
\n

Images

\n

See a visual tour of Route Now, and keep your own image library — upload logos or graphics (or your designer's) and copy a shareable link to use anywhere.

\n \n \n
\n \n {imgBusy && Uploading…}\n
\n {orgImages.length === 0 ? (\n

No images yet — upload one above.

\n ) : (\n
\n {orgImages.map((im) => (\n
\n {im.name}\n
\n \n \n
\n
\n ))}\n
\n )}\n
\n }\n\n {section === 'alerts' && <>\n {/* Editable automated driver-alert SMS text */}\n
\n

Alert messages

\n

Customize the automatic texts sent to drivers when an alert fires. Leave a box blank to use the default wording.

\n \n