{"version":3,"sources":["jsdelivr-header.js","/npm/@labelbox/labeling-api@2.0.0-alpha.2/dist/main.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,ACNA;AACA;AACA","file":"/npm/@labelbox/labeling-api@2.0.0-alpha.2/dist/main.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@labelbox/labeling-api@2.0.0-alpha.2/dist/main.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?t(exports,require(\"tslib\"),require(\"symbol-observable\"),require(\"rxjs/operators\"),require(\"rxjs/add/operator/map\"),require(\"rxjs/add/operator/take\"),require(\"rxjs/add/operator/filter\"),require(\"ts-retry-promise\"),require(\"rxjs\"),require(\"logrocket\"),require(\"redux\"),require(\"redux-observable\"),require(\"ramda\"),require(\"sweetalert\"),require(\"cuid\")):\"function\"==typeof define&&define.amd?define([\"exports\",\"tslib\",\"symbol-observable\",\"rxjs/operators\",\"rxjs/add/operator/map\",\"rxjs/add/operator/take\",\"rxjs/add/operator/filter\",\"ts-retry-promise\",\"rxjs\",\"logrocket\",\"redux\",\"redux-observable\",\"ramda\",\"sweetalert\",\"cuid\"],t):t(e.Labelbox={},e.tslib,null,e.operators,null,null,null,e.tsRetryPromise,e.Rxjs,e.LogRocket,e.Redux,e.ReduxObservable,e.Ramda,e.SweetAlert,e.cuid)}(this,(function(e,t,n,o,a,r,s,i,d,l,c,u,p,m,b){\"use strict\";function I(){return window.location.href}function h(e,t){const{searchParams:n}=new URL(e);return n.get(t)||void 0}function f(e,t){const n=new URL(e);for(const e of t)n.searchParams.delete(e);return n.toString()}var g;function E(){return h(window.location.href,\"local\")?g.DEV:g.PROD}l=l&&l.hasOwnProperty(\"default\")?l.default:l,m=m&&m.hasOwnProperty(\"default\")?m.default:m,b=b&&b.hasOwnProperty(\"default\")?b.default:b,function(e){e.PROD=\"prod\",e.DEV=\"dev\"}(g||(g={})),window.env=window.env||{};const A=e=>{if(window.env&&e in window.env)return window.env[e]},_=A(\"INTERNAL_GRAPHQL_URL\")||{dev:\"http://localhost:3000/api/_gql\",prod:\"https://app.labelbox.com/api/_gql\"}[E()],T={dev:\"http://localhost:3000\",prod:A(\"APP_URL\")||\"https://app.labelbox.com\"}[E()],y=e=>{if(Boolean(localStorage.getItem(\"DEBUG_LABELBOX\"))&&e&&e.query){const t=/^(query|mutation) (\\w+)/.exec(e.query);if(t){const e=t[2];return`${_}?op=${e||\"none\"}`}}return _},S=({headers:e={},body:n})=>t.__awaiter(void 0,void 0,void 0,(function*(){const t=y(n);try{const o=yield window.fetch(t,{method:\"POST\",body:JSON.stringify(n),headers:Object.assign({\"Content-Type\":\"application/json\",\"X-Labelbox-UA\":\"js-sdk/2.0.0-alpha.2\"},e)});return o.ok?o.json():o.text()}catch(e){return Promise.reject(\"Failed to POST JSON due to network issues.\")}})),O=\"true\"===h(window.location.href,\"iframe\");class w{constructor(){this.key=\"labelbox-jwt\"}get(){return localStorage.getItem(this.key)}set(e){return localStorage.setItem(this.key,e)}clear(){return localStorage.removeItem(this.key)}}var j=new class{constructor(e={}){const t=e.currentUrl||I();this.store=e.store||new w;const n=h(t,\"tokenUrlParam\")||null,o=this.getAccessTokenFromHash(t),a=this.store.get();if(this.token=Promise.resolve(a),n&&!e.disableNavigation){const e=f(t,[\"token\"]);window.history.replaceState({},document.title,e)}if(o){e.disableNavigation||history.pushState(\"\",document.title,window.location.pathname+window.location.search);const t=this.getTokenIssuedAt(o);return t?void((!a||t>this.getTokenIssuedAt(a))&&(this.updateStorage(o),this.token=Promise.resolve(o))):void console.log(\"Invalid access token detected. Rejecting and failing back to browsers store\")}n&&this.updateStorage(n),this.token=Promise.resolve(n)}updateStorage(e){return e?this.store.set(e):this.store.clear(),e}getToken(){return t.__awaiter(this,void 0,void 0,(function*(){return(yield this.token)||this.store.get()}))}removeToken(){this.updateStorage(null),this.token=Promise.resolve(null)}getAccessTokenFromHash(e){try{const t=new URL(e);if(!t.hash.length)return null;return new URLSearchParams(t.hash.slice(1)).get(\"accessToken\")}catch(e){return null}}getTokenIssuedAt(e){try{return JSON.parse(atob(e.split(\".\")[1])).iat}catch(e){return}}}({disableNavigation:O});const L=({query:e,variables:n,retries:o=0})=>t.__awaiter(void 0,void 0,void 0,(function*(){const a=yield j.getToken();return(({headers:e={},body:n,retries:o=0})=>t.__awaiter(void 0,void 0,void 0,(function*(){return yield i.retry((()=>S({headers:e,body:n})),{retries:o}).catch((e=>console.error(e)))})))({body:{query:e,variables:n||{}},headers:{authorization:a?`Bearer ${a}`:\"\"},retries:o})}));function v(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield L({query:\"query GetUser {\\n  user {\\n    id\\n    name\\n    email\\n    organization {\\n      id\\n    }\\n  }\\n}\\n\",retries:1});if(!e||!e.data.user)return;const{id:t,name:n,email:o,organization:{id:a}}=e.data.user;return{id:t,name:n,email:o,organizationId:a}}))}const N=(...e)=>{Boolean(localStorage.getItem(\"DEBUG_LABELBOX\"))&&console.log(...e)};let R;const D=()=>R;const C=e=>{let t=0;return(...n)=>{0===t&&(t+=1,e(...n))}};function k(){return!!h(I(),\"configuring\")}const U=A(\"LOG_ROCKET_KEY\"),B=A(\"LOG_ROCKET_HOST\"),x=()=>Boolean(U)&&(void 0===B||\"labeling-api\"===B);if(x()){const e=A(\"RELEASE_TAG\"),t=e?{release:e}:{},n=Object.assign({rootHostname:\"labelbox.com\"},t);l.init(U,n)}function P({id:e,name:t,email:n,organizationId:o},a,r={}){if(!e)return;const s=A(\"SEGMENT_KEY\");if(!s)return void L({query:\"mutation TrackLabelingAPIEvent($name: String!, $properties: Json) {\\n  track(data: { name: $name, properties: $properties }) {\\n    success\\n  }\\n}\\n\",variables:{name:a,properties:r}});const i=btoa(`${s}:`),d=x()&&l.sessionURL||void 0;window.fetch(\"https://api.segment.io/v1/track\",{body:JSON.stringify({sessionURL:d,event:a,properties:Object.assign({organizationId:o,name:t,email:n},r),userId:e}),headers:{Authorization:`Basic ${i}`,\"Content-Type\":\"application/json\"},method:\"POST\"}).catch((e=>{N(`Error recording tracking event: ${e}`)}))}const $=C((e=>{x()&&l.identify(e.id,{name:e.name,email:e.email,preferDarkMode:JSON.parse(localStorage.getItem(\"darkTheme\")||\"false\")})})),M=(e=b)=>{const t=new Map;return{get(n){const o=t.get(n);if(o)return o;const a=e();return t.set(n,a),a},remove:e=>t.delete(e)}},q=e=>{try{return JSON.parse(e)}catch(e){return}};class F{constructor(e){this.payload=e}get labelRef(){return this.payload.labelRef}get dataRowId(){return this.payload.dataRowId}get projectId(){return this.payload.projectId}get templateId(){var e;return null!==(e=this.payload.templateId)&&void 0!==e?e:null}get benchmarkId(){var e;return null!==(e=this.payload.benchmarkId)&&void 0!==e?e:null}encode(){return btoa(JSON.stringify(this.payload))}static decode(e){const t=atob(e),n=q(t);if(n&&F.isPayload(n))return new F(n)}static isPayload(e){var t;return\"string\"==typeof(null===(t=null==e?void 0:e.labelRef)||void 0===t?void 0:t.id)&&\"string\"==typeof(null==e?void 0:e.dataRowId)&&\"string\"==typeof(null==e?void 0:e.projectId)}static isValidLegacyPayload(e){const t=Buffer.from(e,\"base64\").toString(\"ascii\"),n=q(t);if(!n||!F.isPayload(n))return!1;const{projectId:o,dataRowId:a,labelRef:{id:r}}=n;return!!(b.isCuid(o)&&b.isCuid(a)&&b.isCuid(r))}}class H{constructor(){this.graph={},this.placeholderNodes={}}addEdge(e,t){null==this.graph[t]&&(this.placeholderNodes[t]=!0),this.graph[e]?this.graph[e].children.push(t):(this.graph[e]={children:[t]},this.placeholderNodes[e]=!0)}addNodeIfNotExist(e,t){this.graph[e]?this.graph[e].data=t:this.graph[e]={children:[],data:t},delete this.placeholderNodes[e]}}const G=e=>e.projectId,Q=e=>{if(!e.projectId)throw new Error(\"undefined project ID\");return e.projectId},K=e=>((e,t=\"\")=>e.assets[t])(e,(e=>e.currentAsset&&e.currentAsset.id)(e)),V=e=>e&&{id:e.id,dataRowId:e.datarowId,data:e.data,label:e.label,previous:e.previousLabelId,next:e.nextLabelId,createdAt:e.createdAt,createdBy:e.createdBy,typeName:e.typeName,labelTemplateId:e.labelTemplateId,labelTemplates:e.labelTemplates||void 0,externalId:e.externalId,metadata:e.metadata,template:e.template,logId:e.logId,labelingTaskId:e.labelingTaskId,hidden:e.hidden},J=e=>p.values(e.assets).filter((({label:e,labelBeingSaved:t})=>void 0===e&&!t)).sort((({fetchedAt:e},{fetchedAt:t})=>e-t)),z=e=>{const t=J(e)[0];return t?t.id:void 0},X=e=>!k()&&J(e).length<2,Y=e=>e.currentAsset?e.currentAsset.startTime:void 0,Z=e=>e.user,W=e=>Boolean(e.currentAssetHistory[0]),ee=({labelTemplates:e,activePredictionModelId:t})=>{const n=e&&e.find((({predictionModel:e})=>Boolean(e&&e.id===t)));if(n)return n.id;{const t=e&&e.find((({predictionModel:e})=>!Boolean(e)));return t?t.id:void 0}},te=e=>Boolean(e&&e.errors&&e.errors.some((({code:e})=>3007===e))),ne=e=>Boolean(e&&e.errors&&e.errors.some((({message:e})=>\"Please sign in\"===e)));function oe(e){const t=new URL(`${T}`);t.pathname=\"/authenticate-editor\";const n=e||ht;n&&t.searchParams.set(\"redirect_project\",n);new URL(window.location.href).searchParams.forEach(((e,n)=>{t.searchParams.set(n,e)})),window.location.assign(t.href)}function ae(e,t){if(te(t)){const t=Z(e);return function(){const e=document.createElement(\"div\");e.innerHTML='Currently the maximum label size is 256kb. If you are labeling a map please break it into smaller pieces with our <a href=\"https://support.labelbox.com/docs/tiled-imagery\" target=\"_blank\">bounds parameter</a>. Also please reach out to our support team or comment on our <a href=\"https://github.com/Labelbox/Labelbox/issues/102\" target=\"_blank\">github issue</a>. Labelbox is alerted anytime a user hits this error.',m({title:\"Label Exceeds Maximum Supported Size\",content:e})}(),void(t&&P(t,\"Label Update Failed: Label too long\",{alert:!0}))}ne(t)&&oe(e.projectId)}var re;!function(e){e.LOGIN=\"Please Login\",e.UNAUTHORIZED=\"Unauthorized\",e.NOT_FOUND=\"Project not found\",e.NO_MORE_LABELS=\"NO_MORE_LABELS\",e.SKIP_CHECKOUT=\"Checkout disabled\"}(re||(re={}));var se,ie;!function(e){e.Reviewing=\"Reviewing\",e.Labeling=\"Labeling\"}(se||(se={})),function(e){e.SET_MODE=\"SET_MODE\",e.LABEL_SUBMITTED=\"LABEL_SUBMITTED\",e.ASSET_FETCHED=\"ASSET_FETCHED_SUCCESSFULLY\",e.STARTED_FETCHING_ASSET=\"STARTED_FETCHING_ASSET\",e.ASSET_FETCH_FAILED=\"ASSET_FETCH_FAILED\",e.APPLICATION_INIT=\"APPLICATION_INIT\",e.USER_FETCHED_FROM_SERVER=\"USER_FETCHED_FROM_SERVER\",e.USER_CREATED_LABEL=\"USER_CREATED_LABEL\",e.LABEL_SAVE_SUCCESS=\"LABEL_SAVE_SUCCESS\",e.USER_REQUESTED_PREVIOUS_LABEL=\"USER_REQUESTED_PREVIOUS_LABEL\",e.USER_REQUESTED_NEXT_LABEL=\"USER_REQUESTED_NEXT_LABEL\",e.LABEL_HISTORY_FETCHED=\"LABEL_HISTORY_FETCHED\",e.SET_LABEL_AS_CURRENT_ASSET=\"SET_LABEL_AS_CURRENT_ASSET\",e.NO_MORE_ITEMS_TO_LABEL=\"NO_MORE_ITEMS_TO_LABEL\",e.SET_LAST_CURRENT_ASSET=\"SET_LAST_CURRENT_ASSET\",e.USER_REQUESTED_NEXT_UNLABELED_ASSET=\"USER_REQUESTED_NEXT_UNLABELED_ASSET\",e.ASSET_PRELOADED=\"ASSET_PRELOADED\",e.FETCH_ASSET=\"FETCH_ASSET\",e.STATE_INVALID_FOR_LABELING=\"STATE_INVALID_FOR_LABELING\",e.FAILED_TO_SAVE_LABEL=\"FAILED_TO_SAVE_LABEL\",e.FAILED_TO_EXTEND_RESERVATIONS=\"FAILED_TO_EXTEND_RESERVATIONS\",e.RESERVATIONS_EXTENDED=\"RESERVATIONS_EXTENDED\",e.UPDATE_CUSTOMIZATION_OPTIONS=\"UPDATE_CUSTOMIZATION_OPTIONS\",e.ASSET_MARKED_AS_LABELED=\"ASSET_MARKED_AS_LABELED\",e.OBJECT_ANNOTATION_STAGED=\"OBJECT_ANNOTATION_STAGED\",e.QUESTION_ANNOTATION_STAGED=\"QUESTION_ANNOTATION_STAGED\",e.ANNOTATIONS_SUBMITTED=\"ANNOTATIONS_SUBMITTED\",e.ANNOTATIONS_SUBMIT_SUCCESS=\"ANNOTATIONS_SUBMIT_SUCCESS\"}(ie||(ie={}));const de=(e,t)=>Object.assign(Object.assign({},e),{currentAsset:t,currentAssetHistory:[t,...e.currentAssetHistory]}),le={currentAsset:void 0,currentAssetHistory:[],assets:{},preloading:!1,error:null,mode:se.Labeling,currentAnnotations:{objects:{},questions:{}}};function ce(e=le,t){const{type:n,payload:o}=t||{};switch(n){case ie.SET_MODE:return o.mode!==e.mode?Object.assign(Object.assign({},e),{mode:o.mode}):e;case ie.ASSET_FETCHED:{const t=o.startTime?de(e,{id:o.asset.id,startTime:o.startTime}):e;return Object.assign(Object.assign({},t),{fetchingAssetId:o.asset.labelId===e.fetchingAssetId?void 0:e.fetchingAssetId,assets:Object.assign(Object.assign({},e.assets),{[o.asset.id]:o.asset})})}case ie.STARTED_FETCHING_ASSET:return Object.assign(Object.assign({},e),{fetchingAssetId:o});case ie.ASSET_FETCH_FAILED:return Object.assign(Object.assign({},e),{fetchingAssetId:e.fetchingAssetId===o?void 0:e.fetchingAssetId});case ie.LABEL_SUBMITTED:return Object.assign(Object.assign({},e),{error:null});case ie.STATE_INVALID_FOR_LABELING:return console.error(\"An error occurred prepping for label submission.\"),Object.assign(Object.assign({},e),{error:Object.assign(Object.assign({},e.error),{invalidState:o.message})});case ie.ASSET_MARKED_AS_LABELED:{const t=K(e);if(!t)return console.warn(\"Called set as labeled with no current asset\"),e;const{id:n}=t,a=e.assets[n];return(a.label||a.labelId)&&console.warn(\"Asset is already marked as label\"),a.labelId!==o.labelId&&console.warn(\"Existing label has been replaced with a new label\"),Object.assign(Object.assign({},e),{assets:Object.assign(Object.assign({},e.assets),{[n]:Object.assign(Object.assign({},a),{label:o.label,labelId:o.labelId,typeName:o.typeName})})})}case ie.FAILED_TO_SAVE_LABEL:return console.error(\"An error occurred saving the label\"),Object.assign(Object.assign({},e),{error:Object.assign(Object.assign({},e.error),{savingLabel:o.error.errors})});case ie.APPLICATION_INIT:{const{projectId:t,token:n}=o;return Object.assign(Object.assign({},e),{projectId:t,token:n})}case ie.USER_FETCHED_FROM_SERVER:return Object.assign(Object.assign({},e),{user:o.user});case ie.LABEL_SAVE_SUCCESS:return Object.assign(Object.assign({},e),{assets:Object.assign(Object.assign({},e.assets),{[o.assetId]:Object.assign(Object.assign({},e.assets[o.assetId]),{label:o.label,labelBeingSaved:!1,labelId:o.labelId,typeName:o.typeName,createdAt:o.createdAt,createdBy:e.user.email})})});case ie.UPDATE_CUSTOMIZATION_OPTIONS:return Object.assign(Object.assign({},e),{customizationOptions:o.customizationOptions});case ie.LABEL_HISTORY_FETCHED:return Object.assign(Object.assign({},e),{assets:Object.assign(Object.assign({},e.assets),{[o.assetId]:Object.assign(Object.assign({},e.assets[o.assetId]),{previousLabelId:o.previousId,nextLabelId:o.nextId})})});case ie.NO_MORE_ITEMS_TO_LABEL:return Object.assign(Object.assign({},e),{currentAsset:e.currentAssetHistory[0]});case ie.USER_REQUESTED_NEXT_UNLABELED_ASSET:{const t=z(e);if(t){const n=e.currentAssetHistory.find((({id:e})=>t===e));return de(e,Object.assign(Object.assign({},n||{id:t}),{startTime:(new Date).getTime()}))}return Object.assign(Object.assign({},e),{currentAsset:void 0})}case ie.USER_CREATED_LABEL:return Object.assign(Object.assign({},e),{assets:Object.assign(Object.assign({},e.assets),{[o.assetId]:Object.assign(Object.assign({},e.assets[o.assetId]),{labelBeingSaved:!0})})});case ie.SET_LABEL_AS_CURRENT_ASSET:return Object.assign(Object.assign({},e),{currentAsset:void 0});case ie.OBJECT_ANNOTATION_STAGED:return Object.assign(Object.assign({},e),{currentAnnotations:{objects:Object.assign(Object.assign({},e.currentAnnotations.objects),{[o.id]:o.object}),questions:Object.assign({},e.currentAnnotations.questions)}});case ie.QUESTION_ANNOTATION_STAGED:return Object.assign(Object.assign({},e),{currentAnnotations:{objects:Object.assign({},e.currentAnnotations.objects),questions:Object.assign(Object.assign({},e.currentAnnotations.questions),{[o.id]:o.question})}});case ie.ANNOTATIONS_SUBMIT_SUCCESS:return Object.assign(Object.assign({},e),{assets:Object.assign(Object.assign({},e.assets),{[o.assetId]:Object.assign(Object.assign({},e.assets[o.assetId]),{label:\"unused\",labelBeingSaved:!1,labelId:o.labelId})}),currentAnnotations:Object.assign({},le.currentAnnotations)});case ie.ANNOTATIONS_SUBMITTED:default:return e}}const ue=(e,t=!1)=>({type:ie.ASSET_FETCHED,payload:Object.assign({asset:e,current:t},t?{startTime:(new Date).getTime()}:{})}),pe=e=>({type:ie.ASSET_FETCH_FAILED,payload:e}),me=()=>({type:ie.USER_REQUESTED_NEXT_UNLABELED_ASSET,payload:{}}),be=e=>({type:ie.UPDATE_CUSTOMIZATION_OPTIONS,payload:{customizationOptions:e}}),Ie=e=>({type:ie.SET_LABEL_AS_CURRENT_ASSET,payload:{labelId:e}}),he=()=>({type:ie.NO_MORE_ITEMS_TO_LABEL,payload:{}}),fe=({setAsCurrent:e})=>({type:ie.FETCH_ASSET,payload:{setAsCurrent:e}}),ge=e=>({type:ie.OBJECT_ANNOTATION_STAGED,payload:{id:e.id,object:e}}),Ee=e=>({type:ie.QUESTION_ANNOTATION_STAGED,payload:{id:e.id,question:e}});let Ae,_e=new Promise((e=>Ae=e));window.addEventListener(\"load\",(()=>Ae(document.body)));const Te=C((e=>{_e.then((t=>{t.innerHTML=e}))}));var ye;!function(e){e.ProjectHome=\"projectHome\",e.TurnOnRealtime=\"turnOnRealtime\",e.Close=\"close\"}(ye||(ye={}));const Se=p.memoize((e=>L({query:\"query GetProjectPredictionModel($projectId: ID!) {\\n  project(where: { id: $projectId }) {\\n    id\\n    activePredictionModel {\\n      id\\n    }\\n  }\\n}\\n\",variables:{projectId:e}}).then((e=>{const t=e&&e.data&&e.data.project&&e.data.project;return t&&t.activePredictionModel&&t.activePredictionModel.id}))));function Oe({projectId:e},t){0===window.location.href.indexOf(\"file://\")?Te('\\n      Please open this file in a local server.<br><br>\\n      If you look at the url it says \"file://\" and your browser won\\'t let you communicate with the Labelbox server.<br></br>\\n      Dont worry this is easy to fix!<br><br>\\n\\n      If your on chrome you can install <a href=\"https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en\">this extension</a> and then select this folder.<br></br>\\n\\n      OR<br></br>\\n\\n      You can also start a local server via the command line. \"python -m SimpleHTTPServer\" or \"npm install -g http-server; http-server -p 8080\"\\n    '):e||window.location.assign(`${T}/signin?development_url=${window.location.href.split(\"?\")[0]}`),window.addEventListener(\"message\",(({data:e})=>{if(!e)return;const{changeLabel:n,mode:o}=e;n&&t(Ie(n)),o&&t((e=>({type:ie.SET_MODE,payload:{mode:e}}))(o))})),window.top&&window.top.postMessage&&window.top.postMessage({status:\"ready-for-commands\"},\"*\")}const we=p.memoize((function e(n,o,a=0){return function(e){return L({query:\"query GetProjectQueueState($projectId: ID!) {\\n  project(where: { id: $projectId }) {\\n    id\\n    queueIsBuilding\\n  }\\n}\\n\",variables:{projectId:e}}).then((e=>e&&e.data&&e.data.project?!Boolean(e.data.project.queueIsBuilding):(console.log(\"Project not found\",e),!1)))}(n).then((r=>t.__awaiter(this,void 0,void 0,(function*(){return r||(a%10==0&&P(o,\"Queue is stuck building\",{sla:!0,description:\"ProjectId: \"+n}),4===a&&P(o,\"Queue is slow to build\",{frustration:!0,description:\"ProjectId: \"+n}),yield(t=3e3,new Promise((e=>{setTimeout((()=>{e(void 0)}),t)}))),e(n,o,a+1));var t}))))}));function je({projectId:e,shouldBeCurrentAsset:n,assets:o}){const a=p.values(o).filter((({labelId:e})=>!e)).map((({datarowId:e})=>e));return(({projectId:e,dataRowIdsToSkip:t=[]})=>{const{searchParams:n}=new URL(window.location.href);return\"false\"===n.get(\"checkout\")?Promise.reject(re.SKIP_CHECKOUT):new Promise(((n,o)=>{L({query:\"query GetNextRow(\\n  $projectId: ID!\\n  $dataRowIdsToSkip: [ID!]!\\n  $skipQueue: Boolean\\n) {\\n  nextDataRowToLabel(\\n    projectId: $projectId\\n    dataRowIdsToSkip: $dataRowIdsToSkip\\n    skipQueue: $skipQueue\\n  ) {\\n    id\\n    labelingTaskId\\n    rowData\\n    externalId\\n    hidden\\n    labelTemplates {\\n      id\\n      label\\n      predictionModel {\\n        id\\n      }\\n    }\\n    metadata {\\n      id\\n      metaType\\n      metaValue\\n      name\\n    }\\n    eventLog {\\n      id\\n    }\\n    template {\\n      ... on LabelTemplate {\\n        id\\n        __typename\\n        sourceLabel {\\n          id\\n          label\\n        }\\n      }\\n    }\\n  }\\n}\\n\",variables:{projectId:e,dataRowIdsToSkip:t,skipQueue:k()}}).then((e=>{if(!e)return o(re.UNAUTHORIZED);if(e.errors){if(e.errors.some((e=>3008===e.code)))return o(re.UNAUTHORIZED);const t=e.errors[0]&&e.errors[0].functionError;return\"Unauthorized\"===t?o(re.UNAUTHORIZED):\"Project not found\"===t?o(re.NOT_FOUND):\"Please Login\"===t?o(re.LOGIN):(console.error(\"Unknown error for getNextRow\",JSON.stringify(e.errors)),o(re.UNAUTHORIZED))}const t=e.data.nextDataRowToLabel;if(!t)return o(re.NO_MORE_LABELS);const{id:a,labelingTaskId:r,rowData:s,labelTemplates:i,externalId:d,metadata:l,template:c,eventLog:u,hidden:p}=t;n({id:a,rowData:s,labelingTaskId:r,labelTemplates:i,externalId:d,hidden:p,metadata:l,labelLog:u&&u.id,template:c&&\"Prediction\"===c.__typename?null:c})}))}))})({projectId:e,dataRowIdsToSkip:a}).then((o=>t.__awaiter(this,void 0,void 0,(function*(){return o?ue({id:o.id,datarowId:o.id,fetchedAt:(new Date).getTime(),data:o.rowData,labelingTaskId:o.labelingTaskId,label:void 0,labelTemplateId:ee({labelTemplates:o.labelTemplates,activePredictionModelId:yield Se(e)}),labelTemplates:o.labelTemplates,externalId:o.externalId,metadata:o.metadata,template:o.template,logId:o.labelLog,hidden:o.hidden},n):n?he():void 0}))),(t=>{if(t===re.NO_MORE_LABELS){if(n)return he()}else if(t===re.UNAUTHORIZED)oe(e);else{if(t===re.SKIP_CHECKOUT)return;Te(t)}}))}const Le=({dispatch:e,projectId:t,assetId:n,labelId:o})=>{L({query:\"query GetProjectLabelingHistoryCursor($projectId: ID!, $labelId: ID) {\\n  project(where: { id: $projectId }) {\\n    labelingHistoryCursor(where: { labelId: $labelId }) {\\n      previous {\\n        id\\n      }\\n      next {\\n        id\\n      }\\n    }\\n  }\\n}\\n\",variables:{projectId:t,labelId:o}}).then((a=>{const r=a&&a.data.project.labelingHistoryCursor;if(!r)return void console.error(`can't fetch label history cursor for projectID: ${t} and labelID: ${o}`);const{previous:s,next:i}=r;e(((e,t,n)=>({type:ie.LABEL_HISTORY_FETCHED,payload:{assetId:e,previousId:t,nextId:n}}))(n,s&&s.id,i&&i.id))})).catch((e=>console.warn(\"Error occurred loading cursor history \",e)))};function ve(e,n,o){return t.__awaiter(this,void 0,void 0,(function*(){const a=window.location.href,r=h(a,\"label\"),s=(e=>(K(e)||{}).labelId)(e),i=r||s,d=G(e);if(i&&e.currentAsset&&r!==s){const e=function(e,t,n){if(void 0===n)return f(e,[t]);const o=new URL(e);return o.searchParams.set(t,n),o.toString()}(a,\"label\",s);window.history.pushState({path:e},\"\",e)}if(n.type===ie.APPLICATION_INIT)return Oe(n.payload,o),v().then((e=>{e?($(e),o((e=>({type:ie.USER_FETCHED_FROM_SERVER,payload:{user:e}}))(e))):oe(d)}),(()=>oe(d))),n.payload.projectId?void(n.payload.labelId?o(Ie(n.payload.labelId)):o(me())):void console.error(\"Cant load any labels because the project is unknown\",n.payload);if(d){if(n.type===ie.USER_REQUESTED_NEXT_UNLABELED_ASSET){const t=z(e);if(t){const n=e.assets[t];n.previousLabelId&&n.nextLabelId||Le({dispatch:o,projectId:d,assetId:t,labelId:n.label}),X(e)&&o(fe({setAsCurrent:!1}))}else o(fe({setAsCurrent:!0}))}if(n.type===ie.FETCH_ASSET&&(yield we(d,Z(e)||{}),je({projectId:d,shouldBeCurrentAsset:n.payload.setAsCurrent,assets:e.assets}).then((e=>{e&&o(e)}))),n.type===ie.LABEL_SAVE_SUCCESS){const t=K(e);t&&Le({dispatch:o,projectId:d,assetId:t.id,labelId:t.labelId})}if(n.type===ie.SET_LABEL_AS_CURRENT_ASSET){const{labelId:t}=n.payload;if(e.assets[t])return void o(ue(e.assets[t],!0));if(t===e.fetchingAssetId)return;o((e=>({type:ie.STARTED_FETCHING_ASSET,payload:e}))(t));(function({projectId:e,labelId:t}){return L({query:\"query GetLabeledAsset($projectId: ID!, $labelId: ID!) {\\n  project(where: { id: $projectId }) {\\n    label(where: { id: $labelId }) {\\n      id\\n      labelingTaskId\\n      label\\n      createdAt\\n      project {\\n        id\\n      }\\n      createdBy {\\n        email\\n      }\\n      dataRow {\\n        id\\n        rowData\\n        externalId\\n        metadata {\\n          id\\n          metaType\\n          metaValue\\n          name\\n        }\\n      }\\n      eventLog {\\n        id\\n      }\\n      type {\\n        id\\n        name\\n      }\\n    }\\n  }\\n}\\n\",variables:{projectId:e,labelId:t}}).then((e=>{const t=e&&e.data.project,n=t&&t.label;if(n)return{id:n.id,datarowId:n.dataRow.id,data:n.dataRow.rowData,label:n.label,labelId:n.id,externalId:n.dataRow.externalId,createdAt:n.createdAt,createdBy:n.createdBy.email,typeName:n.type.name,metadata:n.dataRow.metadata,projectId:n.project.id,logId:n.eventLog&&n.eventLog.id,labelingTaskId:n.labelingTaskId,fetchedAt:Date.now(),template:null,hidden:!1}}))})({projectId:Q(e),labelId:t}).then((n=>{if(n){if(n.projectId!==d){const o=new URL(window.location.href);o.searchParams.set(\"project\",n.projectId),o.searchParams.set(\"label\",t),o.searchParams.set(\"token\",e.token||\"\");const a=o.href;return window.location.assign(a)}o(ue(n,!0))}else o(pe(t)),oe(d)}),(()=>{o(pe(t)),oe(d)}))}if(n.type===ie.ASSET_FETCHED){if(n.payload.current){const e=n.payload.asset.labelId;Le({dispatch:o,projectId:d,assetId:n.payload.asset.id,labelId:e})}X(e)&&o(fe({setAsCurrent:!1}))}if(n.type===ie.NO_MORE_ITEMS_TO_LABEL){if(e.mode===se.Reviewing)return;const n=yield(e=>t.__awaiter(void 0,void 0,void 0,(function*(){var t;const n=yield L({query:\"query GetProjectLabelCount($projectId: ID!) {\\n  project(where: { id: $projectId }) {\\n    id\\n    labelCount\\n  }\\n}\\n\",variables:{projectId:e}});return n?null!==(t=n.data.project.labelCount)&&void 0!==t?t:0:null})))(d);if(null!==n&&0===n&&k())return m({title:\"Can't preview the editor\",text:\"Queue data to preview the labeling experience\",icon:\"info\",button:!1}),void(document.querySelector(\".swal-overlay\").style=\"background-color: #dddddd;\");(function({canCloseModal:e,userCanTurnOnRealtime:t}){const n={text:\"Close\",value:ye.Close,visible:!0,className:\"\",closeModal:!0},o={text:\"Go to project overview\",value:ye.ProjectHome,visible:!0,className:\"\",closeModal:!0},a={text:\"Wait for next asset\",value:ye.TurnOnRealtime,visible:!0,className:\"\",closeModal:!0},r=window.top!==window.self,s=m(Object.assign({title:\"All done!\",html:\"No more items to label.\",icon:\"success\"},((e,t,r)=>{if(e)return{button:!1,text:\" \"};if(t)return r?{buttons:[o,a]}:{buttons:[n,o]};const s={closeOnClickOutside:!1,closeOnEsc:!1,className:\"no-\"};return r?Object.assign({buttons:[o,a]},s):Object.assign({button:o},s)})(r,e,t)));return e||(document.querySelector(\".swal-overlay\").style=\"background-color: #dddddd;\"),s})({canCloseModal:W(e),userCanTurnOnRealtime:Boolean(e.customizationOptions&&e.customizationOptions.realTime)}).then((t=>{if(t===ye.ProjectHome)window.location.assign(T+\"/projects/\"+d);else if(t===ye.TurnOnRealtime){m({title:\"Waiting for task...\",icon:\"info\",text:\"The next asset will appear automatically when ready. Leave this window open.\",button:!1,closeOnClickOutside:!1,closeOnEsc:!1,className:\"no-\"});const t=setInterval((()=>{je({projectId:d,shouldBeCurrentAsset:!0,assets:e.assets}).then((e=>{e&&e.type===ie.ASSET_FETCHED&&(new Audio(\"https://storage.googleapis.com/labeling-api-assets-prod/slow-spring-board.mp3\").play(),clearInterval(t),m.close(),o(e))}))}),1e4)}}))}}}))}var Ne;(Ne=e.LabelTypes||(e.LabelTypes={})).ANY=\"Any\",Ne.SKIP=\"Skip\";const Re=M(),De=(e,{typeName:t,label:n,templateId:o})=>{const a=K(e),r=Z(e),s=Y(e),i=a.datarowId;return function({id:e,projectId:t,rowId:n,label:o,user:a,secondsToLabel:r,typeName:s,templateId:i}){return P(a,\"Labeled Data\",{labelId:e,typeName:s,secondsToLabel:r}),L({query:\"mutation CreateLabel(\\n  $id: ID!\\n  $label: String!\\n  $secondsToLabel: Float!\\n  $rowId: ID!\\n  $projectId: ID!\\n  $typeName: String!\\n  $templateId: String\\n) {\\n  createLabel(\\n    data: {\\n      id: $id\\n      label: $label\\n      secondsToLabel: $secondsToLabel\\n      dataRow: { connect: { id: $rowId } }\\n      project: { connect: { id: $projectId } }\\n      type: { connect: { name: $typeName } }\\n      templateId: $templateId\\n    }\\n  ) {\\n    id\\n    createdAt\\n    type {\\n      name\\n    }\\n  }\\n}\\n\",variables:{id:e,label:o,projectId:t,rowId:n,secondsToLabel:r,typeName:s,templateId:i}}).then((e=>{const t=e&&e.data&&e.data.createLabel;if(!t)throw e;const{id:o,createdAt:a,type:{name:r}}=t;return{id:o,createdAt:a,assetId:n,typeName:r}}))}({id:Re.get(i),assetId:a.id,projectId:e.projectId,rowId:a.datarowId,label:n,user:r,secondsToLabel:(d=s,l=(new Date).getTime(),Math.abs((d-l)/1e3)),typeName:t,templateId:o||void 0}).then((e=>(Re.remove(i),e)));var d,l},Ce=({maxRetryAttempts:e=3,scalingDuration:t=500,noRetryChecks:n=[]}={})=>a=>a.pipe(o.mergeMap(((o,a)=>{const r=a+1;return console.log(\"Error\",o),r>e||n.some((e=>e(o)))?d.throwError(o):(console.log(`Attempt ${r}: retrying in ${r*t}ms`),d.timer(r*t))}))),ke=new Set;function Ue(e,n,o,a){return t.__awaiter(this,void 0,void 0,(function*(){yield L({query:\"mutation EmitHeartbeatP6s(\\n  $logId: String!\\n  $clientTimestampIso: String!\\n  $timeElapsed: Float!\\n  $mode: LabelLogEventMode\\n) {\\n  emitHeartbeat(\\n    data: {\\n      logId: $logId\\n      clientTimestampIso: $clientTimestampIso\\n      timeElapsed: $timeElapsed\\n      mode: $mode\\n    }\\n  ) {\\n    success\\n  }\\n}\\n\",variables:{logId:e,clientTimestampIso:n,timeElapsed:o,mode:a}})}))}const Be=e=>{const t=Y(e),n=K(e);return Z(e)?e.projectId?n?0===Object.keys(e.currentAnnotations.objects).length&&0===Object.keys(e.currentAnnotations.questions).length?\"No annotations\":t?null:\"Start time not found for asset\":\"No current asset\":\"No current project\":\"User not yet loaded\"},xe=(e,n)=>t.__awaiter(void 0,void 0,void 0,(function*(){const o=e.currentAnnotations;let a;a={labelingTaskId:n.encode(),objects:[],questions:[]};for(const e in o.questions)a.questions.push(o.questions[e]);for(const e in o.objects)a.objects.push(o.objects[e]);return function(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield L({query:\"mutation BatchUpsertAnnotationsP6s($data: BatchUpsertAnnotationsInput!) {\\n  batchUpsertAnnotations(data: $data) {\\n    labelingTaskId\\n  }\\n}\\n\",variables:{data:e}});if(t.errors)throw console.error(`batchUpsertAnnotations failed: ${t.errors[0].message}`),new Error(`batchUpsertAnnotations failed: ${t.errors[0].message}`)}))}(a)})),Pe=(e,n)=>t.__awaiter(void 0,void 0,void 0,(function*(){const o=$e(e);return function(e,n,o){var a,r;return t.__awaiter(this,void 0,void 0,(function*(){const t=yield L({query:\"mutation SubmitLabelingTaskP6s(\\n  $projectId: ID!\\n  $labelingTaskId: ID!\\n  $featureIds: [ID!]!\\n) {\\n  project(where: { id: $projectId }) {\\n    submitLabelingTask(\\n      where: { labelingTaskId: $labelingTaskId, featureIds: $featureIds }\\n    ) {\\n      id\\n    }\\n  }\\n}\\n\",variables:{projectId:e,labelingTaskId:n,featureIds:o}});if(t.errors)throw console.error(`submitLabelingTask failed: ${null===(a=t.errors[0])||void 0===a?void 0:a.message}`),new Error(`submitLabelingTask failed: ${null===(r=t.errors[0])||void 0===r?void 0:r.message}`)}))}(n.projectId,n.encode(),o)})),$e=e=>{const t=[];for(const n in e.currentAnnotations.objects)t.push(n);for(const n in e.currentAnnotations.questions){t.push(n);const o=e.currentAnnotations.questions[n];for(const e of o.options)t.push(e.id)}return t},Me=e=>t.__awaiter(void 0,void 0,void 0,(function*(){const t=K(e);if(!t)throw new Error(\"No current assets\");let n=\"CREATING\";e.mode===se.Reviewing&&(n=\"REVIEWING\");const o=new Date,a=o.toISOString(),r=Y(e);let s=(i=r,d=o.getTime(),Math.abs((i-d)/1e3));var i,d;const l=[];for(;s>0;)l.push(Ue(t.logId,a,Math.min(5,s),n)),s-=5;yield Promise.all(l)}));const qe=u.combineEpics(((n,a)=>{const r=n.pipe(u.ofType(ie.LABEL_SUBMITTED),o.withLatestFrom(a),o.debounceTime(300),o.map((([e,t])=>{const{label:n}=e.payload,o=((e,t)=>{const n=Y(e),o=K(e);if(!Z(e))return\"User not yet loaded\";if(!e.projectId)return\"No current project\";if(!o)return\"No current asset\";if(\"string\"!=typeof t)return\"Label must be a string not \"+typeof t+\". Label: \"+JSON.stringify(t);return n?null:\"Start time not found for asset\"})(t,n);return o?{error:!0,message:o,state:t}:{error:!1,action:e,state:t}}))),s=r.pipe(o.filter((({error:e})=>e)),o.map((({message:e})=>({type:ie.STATE_INVALID_FOR_LABELING,payload:{message:e}})))),i=r.pipe(o.filter((({error:e})=>!e)),o.concatMap((({state:n,action:a})=>d.defer((function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=K(n);if(!a)return console.log(\"Action is undefined\"),{response:null};if(!t)return console.log(\"Error: CurrentAsset is undefined\"),{response:null};const{datarowId:o}=t,{label:r,typeName:s,templateId:i}=a.payload,d=s||t.typeName||e.LabelTypes.ANY;let l;if(t.label&&t.labelId){if(N(`Updating ${o}`),!t.labelId)return console.log(\"Error: CurrentAsset.labelId is Undefined\"+JSON.stringify(t)),{response:null};l=function(e,t,n){return L({query:\"mutation UpdateLabel($id: ID!, $label: String!, $typeName: String!) {\\n  updateLabel(\\n    where: { id: $id }\\n    data: { label: $label, type: { connect: { name: $typeName } } }\\n  ) {\\n    id\\n    createdAt\\n    updatedAt\\n    type {\\n      name\\n    }\\n  }\\n}\\n\",variables:{id:e,label:t,typeName:n}}).then((e=>{const t=e&&e.data&&e.data.updateLabel;if(!t)throw e;const{id:n,createdAt:o,updatedAt:a,type:{name:r}}=t;return{id:n,createdAt:o,updatedAt:a,assetId:n,typeName:r}}))}(t.labelId,r,d)}else ke.has(o)?(N(`Aborting any action. Asset ${t.datarowId} was already labeled.`),l=Promise.resolve(null)):(N(`Saving ${o}`),l=De(n,{label:r,typeName:d,templateId:i}).then((e=>(ke.add(o),e))));return l.then((e=>({response:e,action:a})))}))})).pipe(o.filter((e=>null!==e.response)),o.retryWhen(Ce({maxRetryAttempts:5,noRetryChecks:[te,ne]})),o.map((({response:{id:e,createdAt:t,assetId:n,typeName:o},action:a})=>((e,t,n,o,a)=>({type:ie.LABEL_SAVE_SUCCESS,payload:{assetId:e,label:t,labelId:n,typeName:o,createdAt:a}}))(n,a.payload.label,e,o,t))),o.catchError((e=>(ae(n,e),d.of({type:ie.FAILED_TO_SAVE_LABEL,payload:{error:e}}))))))));return d.merge(s,i)}),(e=>e.ofType(ie.ASSET_FETCHED).pipe(o.filter((e=>!e.payload.current)),o.mergeMap((e=>{const t=D();if(!t)return d.of(!1);const n=V(e.payload.asset);if(!n)return console.error(\"Unable to preload undefined asset\"),d.of(!1);try{const e=t(n);return\"function\"!=typeof e.then?(console.error(\"Preloading function must return a promise that resolves when the asset is loaded.\"),d.of(!1)):d.defer((()=>e.then((()=>n)).catch((e=>(console.warn(\"Error occurred preloading next asset:\",e),!1)))))}catch(e){return console.warn(\"Error occurred preloading next asset:\",e),d.of(!1)}})),o.filter(Boolean),o.map((e=>{return t=e.id,{type:ie.ASSET_PRELOADED,payload:{assetId:t}};var t})))),((e,n)=>k()?d.empty():e.pipe(o.take(1),o.withLatestFrom(n),o.switchMap((e=>n.pipe(o.map(G),o.filter(Boolean),o.distinctUntilChanged()))),o.switchMap((e=>d.timer(0,6e5).pipe(o.switchMap((()=>(console.log(`Calling extend reservation for the projectId=${e} from the ten minute timer epic`),d.defer((()=>function(e,n){return t.__awaiter(this,void 0,void 0,(function*(){if(n)return e({query:\"mutation ExtendReservations($projectId: ID!) {\\n  extendReservations(projectId: $projectId, queueType: LabelingQueue)\\n}\\n\",variables:{projectId:n}})}))}(L,e))).pipe(o.retryWhen(Ce({maxRetryAttempts:3})),o.map((()=>({type:ie.RESERVATIONS_EXTENDED,payload:{}}))),o.catchError((()=>d.of({type:ie.FAILED_TO_EXTEND_RESERVATIONS,payload:{}})))))))))))),((e,n)=>{const a=e.pipe(u.ofType(ie.ANNOTATIONS_SUBMITTED),o.withLatestFrom(n),o.debounceTime(300),o.map((([e,t])=>{const n=Be(t);return n?{error:!0,message:n,state:t}:{error:!1,action:e,state:t}}))),r=a.pipe(o.filter((({error:e})=>e)),o.map((({message:e})=>({type:ie.STATE_INVALID_FOR_LABELING,payload:{message:e}})))),s=a.pipe(o.filter((({error:e})=>!e)),o.concatMap((({state:e,action:n})=>d.defer((function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=(e=>{const t=e.projectId;if(!t)throw new Error(\"project id is empty\");const n=K(e);if(!n)throw new Error(\"current asset is empty\");const o=M(),a=!!n.labelId;return new F({labelRef:{existing:a,id:(null==n?void 0:n.labelId)||o.get(n.datarowId)},dataRowId:n.datarowId,projectId:t})})(e);return yield xe(e,t),yield Me(e),yield Pe(e,t),{response:{labelingTaskId:t},action:n}}))})).pipe(o.filter((e=>null!==e.response)),o.map((({response:e})=>{return t={assetId:e.labelingTaskId.dataRowId,labelId:e.labelingTaskId.encode()},{type:ie.ANNOTATIONS_SUBMIT_SUCCESS,payload:t};var t})),o.catchError((t=>(ae(e,t),d.of({type:ie.FAILED_TO_SAVE_LABEL,payload:{error:t}}))))))));return d.merge(r,s)})),Fe=u.createEpicMiddleware(),He=[e=>t=>n=>{N(\"dispatching\",n);let o=t(n);return N(\"next state\",e.getState()),o},Fe,({dispatch:e,getState:t})=>n=>o=>{const a=n(o);return ve(t(),o,e),a}];x()&&He.push(l.reduxMiddleware());const Ge=(()=>{const e=c.createStore(ce,c.applyMiddleware(...He));return Fe.run(qe),e})(),Qe=new d.BehaviorSubject(Ge.getState()),Ke=()=>Ge.getState();Ge.subscribe((()=>Qe.next(Ge.getState())));const Ve=e=>{Ge.dispatch(e)};var Je,ze,Xe;function Ye(e,t,n,o){const a=e.findIndex(t);a>-1?n(a):e.push(o())}!function(e){e.CREATING=\"CREATING\",e.EDITING=\"EDITING\",e.REVIEWING=\"REVIEWING\"}(Je||(Je={})),(ze=e.AttachmentType||(e.AttachmentType={})).HTML=\"HTML\",ze.IMAGE=\"IMAGE\",ze.IMAGE_OVERLAY=\"IMAGE_OVERLAY\",ze.RAW_TEXT=\"RAW_TEXT\",ze.TEXT=\"TEXT\",ze.TEXT_URL=\"TEXT_URL\",ze.VIDEO=\"VIDEO\",function(e){e.agreement_ASC=\"agreement_ASC\",e.agreement_DESC=\"agreement_DESC\",e.benchmarkAgreement_ASC=\"benchmarkAgreement_ASC\",e.benchmarkAgreement_DESC=\"benchmarkAgreement_DESC\",e.createdAt_ASC=\"createdAt_ASC\",e.createdAt_DESC=\"createdAt_DESC\",e.deleted_ASC=\"deleted_ASC\",e.deleted_DESC=\"deleted_DESC\",e.id_ASC=\"id_ASC\",e.id_DESC=\"id_DESC\",e.label_ASC=\"label_ASC\",e.label_DESC=\"label_DESC\",e.secondsToLabel_ASC=\"secondsToLabel_ASC\",e.secondsToLabel_DESC=\"secondsToLabel_DESC\",e.updatedAt_ASC=\"updatedAt_ASC\",e.updatedAt_DESC=\"updatedAt_DESC\"}(Xe||(Xe={}));class Ze{constructor(e){this.data=[],this.compareFn=e}insert(e){this.data.push(e),this.data.sort(this.compareFn)}delete(e){this.data.splice(e,1)}find(e){return this.data.find(e)}findIndex(e){return this.data.findIndex(e)}}function We(e){return\"function\"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function et(e,t){return{geometry:{type:e,coordinates:t}}}function tt(e){if(2!==e.length)throw new Error(\"Bounding box must contain two coordinates\");const[t,n]=e;return et(\"MultiPolygon\",[[[t,[t[0],n[1]],n,[n[0],t[1]],t]]])}function nt(e){if(e.length<4||JSON.stringify(e[0])!==JSON.stringify(e[e.length-1]))throw new Error(\"Polygon must contain at least 4 coordinates and the first and last coordinate must be identical\");return et(\"MultiPolygon\",[[e]])}function ot(e){if(e.length<2)throw new Error(\"Polyline must contain at least 2 coordinates\");return et(\"MultiLineString\",[e])}function at(e){return et(\"Point\",e)}function rt(e){if(e.length<1)throw new Error(\"Multipolygon must contain at least 1 polygon\");for(const t of e)if(t.length<4||JSON.stringify(t[0])!==JSON.stringify(t[t.length-1]))throw new Error(\"Polygon must contain at least 4 coordinates and the first and last coordinate must be identical\");return et(\"MultiPolygon\",[e])}class st extends Error{}const it=new class{createQuestionAnnotation(e,t,n){if(0===t.length)throw new Error(\"Question annotation require at least one answer\");if(this.existsQuestionAnnotation(e,n))throw console.error(`Question with schemaId ${e} and parentId ${n} already exists. Call updateQuestionAnnotation instead?`),new Error(`Question with schemaId ${e} and parentId ${n} already exists`);const o=this._createFeatureId(),a=[];for(const e of t)a.push({id:this._createFeatureId(),schemaId:e,content:{},deleted:!1});return this._dispatch(Ee({parentId:n,id:o,schemaId:e,content:{},deleted:!1,options:a})),{question:{featureId:o},answers:a.reduce(((e,t)=>(e[t.schemaId]={featureId:t.id},e)),{})}}updateQuestionAnnotation(e,t,n){const o=e,a=this.getQuestionAnnotation(e),r=a.schemaId,s=a.options.map((e=>Object.assign(Object.assign({},e),{deleted:!0})));for(const e of t)Ye(s,(t=>t.schemaId===e),(e=>s[e].deleted=!1),(()=>({id:this._createFeatureId(),schemaId:e,content:{},deleted:!1})));return this._dispatch(Ee({parentId:n,id:o,schemaId:r,content:{},deleted:!1,options:s})),{question:{featureId:o},answers:s.reduce(((e,t)=>(e[t.schemaId]={featureId:t.id},e)),{})}}createObjectAnnotation(e){return(t,n)=>{const o=this._createFeatureId(),a={id:o,schemaId:t,content:e(n),deleted:!1};return this._dispatch(ge(a)),o}}updateObjectAnnotation(e){return(t,n)=>{const o=this.getObjectAnnotation(t),a={id:o.id,schemaId:o.schemaId,content:e(n),deleted:!1};return this._dispatch(ge(a)),o.id}}deleteObjectAnnotation(e){const t=this.getObjectAnnotation(e);t.deleted=!0,this._dispatch(ge(t))}deleteQuestionAnnotation(e){const t=this.getQuestionAnnotation(e);t.deleted=!0;const n=[];for(const e of t.options)e.deleted=!0,n.push(e.id);return this._dispatch(Ee(t)),n}deleteOptionAnnotation(e,t){const n=this.getQuestionAnnotation(e);let o=!1;for(const e of n.options)e.id===t&&(e.deleted=!0,o=!0);if(!o)throw new Error(`Expected to find option ${t} but it is missing`);this._dispatch(Ee(n))}getDeletionList(e){var t,n;const o=this._getState(),a=(e=>{const t=e.currentAnnotations,n=new H;for(const e of Object.values(t.objects).filter((e=>!e.deleted)))n.addNodeIfNotExist(e.id,{annotation:e,type:\"object\"});for(const e of Object.values(t.questions).filter((e=>!e.deleted))){n.addNodeIfNotExist(e.id,{annotation:e,type:\"question\"}),e.parentId&&n.addEdge(e.parentId,e.id);for(const t of e.options.filter((e=>!e.deleted)))n.addNodeIfNotExist(t.id,{annotation:t,type:\"option\"}),n.addEdge(e.id,t.id)}return n.graph})(o),r={objects:[],questions:[],options:[]};if(null==a[e])return r;const s=[e];for(;s.length>0;){const e=s.shift(),n=a[e];switch(null===(t=n.data)||void 0===t?void 0:t.type){case\"object\":r.objects.push(e);break;case\"question\":r.questions.push(e)}if(null==n)throw new Error(`Logical error: expected to find feature ${e} but it does not exist`);for(const e of n.children)s.push(e)}if(\"option\"===(null===(n=a[e].data)||void 0===n?void 0:n.type)){let t;for(const n of Object.values(o.currentAnnotations.questions))if(n.options.find((t=>t.id===e))){t=n.id;break}if(null==t)throw new Error(`Expected option (${e}) to have a parent question but none was found`);r.options.push({questionId:t,optionId:e}),1===a[t].children.length&&r.questions.push(t)}return r}getQuestionAnnotation(e){const t=this._getState().currentAnnotations.questions[e];if(null==t)throw new st(`Question featureID ${e} does not exist`);return We(t)}getObjectAnnotation(e){const t=this._getState().currentAnnotations.objects[e];if(null==t)throw new st(`Object featureID ${e} does not exist`);return We(t)}existsQuestionAnnotation(e,t){const n=this._getState().currentAnnotations.questions;return-1<Object.values(n).findIndex((n=>n.schemaId===e&&n.parentId===t))}_createFeatureId(){return b()}_dispatch(e){Ve(e)}_getState(){return Ke()}};const dt=new class{constructor(){this.createBoundingBoxAnnotation=it.createObjectAnnotation(tt),this.updateBoundingBoxAnnotation=it.updateObjectAnnotation(tt),this.createPolygonAnnotation=it.createObjectAnnotation(nt),this.updatePolygonAnnotation=it.updateObjectAnnotation(nt),this.createPolylineAnnotation=it.createObjectAnnotation(ot),this.updatePolylineAnnotation=it.updateObjectAnnotation(ot),this.createPointAnnotation=it.createObjectAnnotation(at),this.updatePointAnnotation=it.updateObjectAnnotation(at),this.createSegmentationAnnotation=it.createObjectAnnotation(rt),this.updateSegmentationAnnotation=it.updateObjectAnnotation(rt)}createRadioQuestionAnnotation(e,t,n){if(null==t||0===t.length||\"string\"!=typeof t)throw new Error(\"Radio questions must contain exactly one answer\");return it.createQuestionAnnotation(e,[t],n)}updateRadioQuestionAnnotation(e,t,n){if(null==t||0===t.length||\"string\"!=typeof t)throw new Error(\"Radio questions must contain exactly one answer\");return it.updateQuestionAnnotation(e,[t],n)}createChecklistQuestionAnnotation(e,t,n){if(null==t||0===t.length||!Array.isArray(t))throw new Error(\"Checklist questions must contain at least one answer\");return it.createQuestionAnnotation(e,t,n)}updateChecklistQuestionAnnotation(e,t,n){if(null==t||0===t.length||!Array.isArray(t))throw new Error(\"Checklist questions must contain at least one answer\");return it.updateQuestionAnnotation(e,t,n)}createTextAnnotation(e,t,n){if(null==t||0===t.length)throw new Error(\"Empty strings are not allowed for text annotations\");if(it.existsQuestionAnnotation(e,n))throw console.error(`Question with schemaId ${e} and parentId ${n} already exists. Update instead?`),new Error(`Question with schemaId ${e} and parentId ${n} already exists`);const o=it._createFeatureId();return it._dispatch(Ee({parentId:n,id:o,schemaId:e,content:{value:t},deleted:!1,options:[]})),o}updateTextAnnotation(e,t,n){if(null==t||0===t.length)throw new Error(\"Empty strings are not allowed for text annotations\");const o=e,a=it.getQuestionAnnotation(e).schemaId;return it._dispatch(Ee({parentId:n,id:o,schemaId:a,content:{value:t},deleted:!1,options:[]})),o}submitAnnotationsForAsset(){var e;Ve((e={},{type:ie.ANNOTATIONS_SUBMITTED,payload:e}));const t=Qe.pipe(o.map((e=>K(e))),o.filter((e=>Boolean(e&&\"unused\"===e.label&&!e.labelBeingSaved))),o.map((e=>{if(e)return{dataRowId:e.datarowId,data:e.data,label:e.label}}))),n=Qe.pipe(o.filter((e=>Boolean(e.error))),o.map((e=>e.error)),o.mergeMap((e=>d.throwError(e))));return d.merge(t,n).pipe(o.take(1)).toPromise()}deleteAnnotation(e){const t=it.getDeletionList(e);let n=[];for(const e of t.objects)it.deleteObjectAnnotation(e),n.push(e);for(const e of t.questions){const t=it.deleteQuestionAnnotation(e);n.push(e),n=n.concat(t)}for(const e of t.options)it.deleteOptionAnnotation(e.questionId,e.optionId),n.push(e.optionId);return n}};var lt;!function(e){e.TextLocation=\"text.location\",e.PdfLocation=\"pdf.location\",e.Edge=\"edge\",e.KeyframesEdge=\"keyframes.edge\",e.Cuboid=\"cuboid\",e.KeyframesCuboid=\"keyframes.cuboid\",e.KeyframesOption=\"keyframes.option\",e.KeyframesQuestionSelection=\"keyframes.question.selection\",e.KeyframesGeoJSONRectangle=\"keyframes.geojson.rectangle\",e.KeyframesGeoJSONLine=\"keyframes.geojson.line\",e.KeyframesGeoJSONPoint=\"keyframes.geojson.point\",e.KeyframesRasterSegmentation=\"keyframes.raster.segmentation\",e.KeyframesRasterSegmentationGroup=\"keyframes.raster.segmentation-group\",e.RasterSegmentation=\"raster.segmentation\",e.RasterSegmentationGroup=\"raster.segmentation-group\",e.IndexOption=\"index.option\",e.IndexQuestionSelection=\"index.question.selection\"}(lt||(lt={}));class ct{static makeBoundingBox(){return new pt(lt.KeyframesGeoJSONRectangle)}static makePolyline(){return new pt(lt.KeyframesGeoJSONLine)}static makePoint(){return new pt(lt.KeyframesGeoJSONPoint)}}ct.makeBoundingBoxKeyframe=(e,t)=>new ut(lt.KeyframesGeoJSONRectangle,e,tt(t)),ct.makePolylineKeyframe=(e,t)=>new ut(lt.KeyframesGeoJSONLine,e,ot(t)),ct.makePointKeyframe=(e,t)=>new ut(lt.KeyframesGeoJSONPoint,e,at(t));class ut{constructor(e,t,n){if(this.format=e,this.frame=t,this.content=n,!Number.isFinite(t))throw new Error(\"frame must be a number\")}}class pt{constructor(e){this._format=e,this._segmentsById=new Map}get format(){return this._format}toJson(){const e=Array.from(this._segmentsById.values()).map((e=>e.toJson()));return{format:this.format,data:e}}_toApiJson(){const e=Array.from(this._segmentsById.values()).map((e=>e._toApiJson()));return{format:this.format,data:e}}createSegment(){const e=new mt(this.format);return this._segmentsById.set(e.Id,e),e}removeSegment(e){return this._segmentsById.delete(e.Id)}findSegment(e){for(const t of this._segmentsById.values()){const[n,o]=t.getRange();if(null!=n&&(n<=e&&e<=o))return t}}validate(){if(this._segmentsById.size<1)throw new Error(\"There must be at least one segment\");for(const e of this._segmentsById.values())e.validate();this._hasOverlappingIntervals()}_hasOverlappingIntervals(){const e=Array.from(this._segmentsById.values());if(e.sort(((e,t)=>{const[n,o]=e.getRange(),[a,r]=t.getRange();if([n,o,a,r].some((e=>null==e)))throw new Error(\"Segment cannot be empty\");return n-a})),1!==e.length)for(let t=1;t<e.length;t++){const n=t-1;if(e[t].getRange()[0]<=e[n].getRange()[1])throw new Error(`Segments cannot overlap: [${e[n].getRange()}], [${e[t].getRange()}]`)}}}class mt{constructor(e){this._format=e,this._keyframes=new Ze(((e,t)=>e.frame-t.frame)),this._id=b()}get Id(){return this._id}get _data(){return this._keyframes.data}getKeyframes(){return this._data.values()}addKeyframe(e){if(this._format!==e.format)throw new Error(`Mismatch between segment and keyframe formats: expected ${this._format} but ${e.format} received`);const{frame:t}=e;if(this._keyframes.findIndex((e=>e.frame===t))>-1)throw new Error(\"Segment cannot contain duplicated key frames\");this._keyframes.insert(e)}removeKeyframe(e){const t=this._keyframes.findIndex((t=>t.frame===e));return-1!==t&&(this._keyframes.delete(t),!0)}getRange(){return 0===this._data.length?[void 0,void 0]:1===this._data.length?[this._data[0].frame,this._data[0].frame]:[this._data[0].frame,this._data[this._data.length-1].frame]}getKeyframeCount(){return this._data.length}validate(){if(0===this._data.length)throw new Error(\"Segment must not be empty\")}_toApiJson(){return{keyframes:this._data.map((e=>({isInferred:!1,frame:e.frame,content:e.content})))}}toJson(){return{keyframes:this._data.map((e=>Object.assign({isInferred:!1},e)))}}}const bt=new class{constructor(){this.createKeyframeAnnotation=(e,t)=>{t.validate();const n=this.createFeatureId(),{data:o,format:a}=t._toApiJson();return Ve(ge({id:n,schemaId:e,content:{version:1,format:a,data:o},deleted:!1})),n},this.updateKeyframeAnnotation=(e,t)=>{t.validate();const n=function(e){const t=Ke().currentAnnotations.objects[e];if(null==t)throw Error(`Object featureID ${e} does not exist`);return structuredClone(t)}(e),{data:o,format:a}=t._toApiJson(),r={id:n.id,schemaId:n.schemaId,content:{version:1,format:a,data:o},deleted:!1};return Ve(ge(r)),n.id}}createFeatureId(){return b()}},It=window.location.href,ht=h(It,\"project\");function ft(){window.addEventListener(\"load\",(()=>j.getToken().then((e=>{Ve((({projectId:e,token:t,labelId:n})=>({type:ie.APPLICATION_INIT,payload:{projectId:e,token:t,labelId:n}}))({projectId:ht,labelId:h(It,\"label\"),token:e}))}))))}function gt(e,t,n){throw console.error(\"setLabelForAsset is no longer supported in labeling-api v2+. If you have accidentally upgraded, then pin to version 1.1.2.\"),new Error(\"setLabelForAsset is no longer supported\")}const Et=function({projectId:e}){const t=e?L({query:\"query GetTemplateCustomization($projectId: ID!) {\\n  project(where: { id: $projectId }) {\\n    id\\n    ontology {\\n      id\\n      normalized\\n      groupOrder\\n    }\\n  }\\n}\\n\",variables:{projectId:e}}).then((e=>{const{normalized:t,groupOrder:n,id:o}=e.data.project.ontology;return Object.assign(Object.assign({},t),{groupOrder:n,ontologyId:o})})).then((t=>(t||N(`Error: No ontology found for projectId: '${e}'`),Ve(be(t)),t))).catch((()=>null)):Promise.resolve({tools:[],classifications:[]});let n=[];return window.addEventListener(\"message\",(({data:e})=>{e&&e.customizationUpdate&&n.forEach((t=>{t(e.customizationUpdate),Ve(be(e.customizationUpdate))}))})),function(){return{subscribe:e=>(n.push(e),t.then((t=>{t&&e(t)})),{unsubscribe:function(){const t=n.indexOf(e);n=[...n.slice(0,t),...n.slice(t+1)]}})}}}({projectId:ht});const At=M;ft(),e.initialProjectId=ht,e.init=ft,e.setLabelForAsset=gt,e.fetchNextAssetToLabel=function(){const e=K(Ke()),t=e&&e.id,n=Qe.pipe(o.map(K),o.filter((e=>Boolean(e&&e.id!==t))),o.map((e=>e.data)),o.take(1)).toPromise();return Ve(me()),n},e.setLabelAsCurrentAsset=e=>Ve(Ie(e)),e.getTemplateCustomization=Et,e.currentAsset=()=>{const e=Qe.pipe(o.map(K),o.map(V),o.distinctUntilChanged(((e,t)=>p.equals(e,t))),o.tap((e=>N(\"Emitting asset: \",e))));return{subscribe:t=>{const n=e.subscribe(t);return{unsubscribe:()=>{n.unsubscribe()}}},_pipe1:t=>e.pipe(t)}},e.skip=()=>gt(0,e.LabelTypes.SKIP),e.update=()=>gt(0,e.LabelTypes.ANY),e.enablePreloading=({preloadFunction:e})=>{\"function\"==typeof e?(e=>{if(R)throw new Error(\"Error: A preloading function has been registered already, and only one can be registered at a time.\");R=e})(e):console.error(\"Please call Labelbox.enablePreloading({preloadFunction: YOUR_FUNCTION_TO_PRELOAD}).\")},e.markAssetAsLabeled=function({label:e,labelId:t,typeName:n}){var o;return Ve((o={label:e,labelId:t,typeName:n},{type:ie.ASSET_MARKED_AS_LABELED,payload:o})),!0},e.getCurrentUser=()=>t.__awaiter(void 0,void 0,void 0,(function*(){const e=yield v();if(e){const{id:t,email:n,name:o,organizationId:a}=e;return{id:t,email:n,name:o,organizationId:a}}return null})),e._createIdFactory=At,e.annotations=dt,e.debugState=function(){return Ke()},e.keyframeAnnotationBuilder=ct,e.keyframeAnnotations=bt,Object.defineProperty(e,\"__esModule\",{value:!0})}));\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sInNvdXJjZXMiOltdLCJtYXBwaW5ncyI6IiIsImlnbm9yZUxpc3QiOltdfQ=="]}