balena-sdk
Version:
The Balena JavaScript SDK
3 lines • 671 kB
JavaScript
!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).balenaSdk=e()}(function(){return function r(i,o,a){function s(t,e){if(!o[t]){if(!i[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}n=o[t]={exports:{}},i[t][0].call(n.exports,function(e){return s(i[t][1][e]||e)},n,n.exports,r,i,o,a)}return o[t].exports}for(var l="function"==typeof require&&require,e=0;e<a.length;e++)s(a[e]);return s}({1:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});n.default=function(e,t){let{auth:n,request:r}=e,i=t.apiUrl;async function o(e){e=(await r.send({method:"POST",url:"/auth/totp/verify",baseUrl:i,body:{code:e}})).body;return e}return{isEnabled:async function(){return"not_required"!==await n.get2FAStatus()},isPassed:async function(){return!await n.needs2FA()},getSetupKey:async function(){var e=(await r.send({method:"GET",url:"/auth/totp/setup",baseUrl:i})).body;return e},enable:async e=>{e=await o(e);return await n.setKey(e),e},verify:o,challenge:async function(e){e=await o(e),await n.setKey(e)},disable:async function(e){return e=(await r.send({method:"POST",url:"/auth/totp/disable",baseUrl:i,body:{password:e}})).body,await n.setKey(e),e}}}},{}],2:[function(h,e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=h("tslib");let m=n.__importStar(h("balena-errors")),g=n.__importDefault(h("memoizee"));t.default=function(e,t){let{auth:r,pubsub:i,request:n,pine:o}=e,a=t.apiUrl,s=function(e){return 401===e.statusCode||"BalenaMalformedToken"===e.code?new m.BalenaNotLoggedIn:e};var l=(t,n)=>async function(...e){try{return await n.apply(r,e)}finally{i.publish(t)}};let c=Object.assign(Object.assign({},r),{setKey:l("auth.keyChange",r.setKey),removeKey:l("auth.keyChange",r.removeKey)});l=h("./2fa").default(Object.assign(Object.assign({},e),{auth:c}),t);let u=(0,g.default)(async()=>{var e=(await n.send({method:"GET",url:"/actor/v1/whoami",baseUrl:a})).body;return e},{primitive:!0,promise:!0}),p=async(e=!1)=>{e&&u.clear();try{return await u()}catch(e){throw s(e)}};async function f(e){try{var t=(await n.send({method:"POST",baseUrl:a,url:"/login_",body:{username:e.email,password:String(e.password)},sendToken:!1})).body;return t}catch(e){if(401===e.statusCode)throw new m.BalenaInvalidLoginCredentials;if(429===e.statusCode)throw new m.BalenaTooManyRequests;throw e}}async function d(){var e=await p();if("user"!==e.actorType)throw new Error("The authentication credentials in use are not of a user");return{id:e.actorTypeId,actor:e.id,email:e.email,username:e.username}}return{twoFactor:l,whoami:async function(){try{return await p()}catch(e){if(!(e instanceof m.BalenaNotLoggedIn))throw e}},authenticate:f,login:async function(e){u.clear(),e=await f(e),await c.setKey(e)},loginWithToken:async function(e){return u.clear(),c.setKey(e)},isLoggedIn:async function(){try{return await p(!0),!0}catch(e){if(e instanceof m.BalenaNotLoggedIn||e instanceof m.BalenaExpiredToken)return!1;throw e}},getToken:function(){return c.getKey().catch(function(e){throw s(e)})},getActorId:async function(){return(await p()).id},getUserInfo:d,logout:async function(){return u.clear(),c.removeKey()},register:async function(e){return e=(await n.send({method:"POST",url:"/user/register",baseUrl:a,body:e,sendToken:!1})).body},verifyEmail:async function(e){var t=e.email,e=e.token;return e=(await n.send({method:"POST",url:"/user/v1/verify-email",body:{verificationToken:e,email:t},baseUrl:a,sendToken:!1})).body},requestVerificationEmail:async function(){var e=(await d()).id;await o.patch({resource:"user",id:e,body:{has_been_sent_verification_email:!0}})}}}},{"./2fa":1,"balena-errors":60,memoizee:416,tslib:564}],3:[function(f,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.fromSharedOptions=t.setSharedOptions=t.getSdk=void 0;var n=f("tslib");let r=f("./util/global-env"),i=(n.__exportStar(f("./types/models"),t),n.__exportStar(f("./types/jwt"),t),n.__exportStar(f("./types/contract"),t),n.__exportStar(f("./types/user-invite"),t),n.__exportStar(f("./types/auth"),t),"BALENA_SDK_SHARED_OPTIONS"),o="BALENA_SDK_HAS_USED_SHARED_OPTIONS",a="BALENA_SDK_HAS_SET_SHARED_OPTIONS",d={auth(){return f("./auth").default},models(){return f("./models")},logs(){return f("./logs").default},settings(){return f("./settings").default}};t.getSdk=function(e){let t,i=Object.assign({apiUrl:"https://api.balena-cloud.com/",builderUrl:"https://builder.balena-cloud.com/",isBrowser:"undefined"!=typeof window&&null!==window,apiVersion:"v7"},e),n=f("./util/sdk-version").default;var e=f("balena-request").getRequest,r=f("balena-auth").default,o=f("./pine").createPinejsClient,a=f("balena-errors"),s=f("./util/pubsub").PubSub,l=f("./util/settings-client").loadSettingsClient(i),r=(i.isBrowser||null!=i.dataDirectory||(i.dataDirectory=l.get("dataDirectory")),"apiKey"in i&&delete i.apiKey,new r(i));let c=e(Object.assign(Object.assign({},i),{auth:r}));null!=i.requestLimit&&0<i.requestLimit&&(e=f("p-throttle"),c.send=e({limit:i.requestLimit,interval:null!=(t=i.requestLimitInterval)?t:6e4,strict:!0})(c.send));e=o({},Object.assign(Object.assign({},i),{auth:r,request:c})),o=new s;let u={},p={settings:l,request:c,auth:r,pine:e,pubsub:o,sdkInstance:u};return Object.keys(d).forEach(function(t){Object.defineProperty(u,t,{enumerable:!0,configurable:!0,get(){var e=d[t]();return delete this[t],this[t]=e(p,i)}})}),Object.defineProperty(u,"interceptors",{get(){return c.interceptors},set(e){return c.interceptors=e}}),Object.defineProperty(u,"utils",{enumerable:!0,configurable:!0,get(){var{mergePineOptions:e,BalenaWebResourceFile:t}=f("./util");return{mergePineOptions:e,BalenaWebResourceFile:t}}}),u.interceptors.push({request(e){let t=e.url;return"string"==typeof t&&0===(t="string"==typeof e.baseUrl?e.baseUrl+t:t).indexOf(i.apiUrl)&&(e.headers["X-Balena-Client"]="balena-sdk/"+n),e}}),i.retryRateLimitedRequests&&u.interceptors.push({async responseError(e){if(!(e instanceof u.errors.BalenaRequestError)||429!==e.statusCode)throw e;var t=e.requestOptions;if(!t.doNotRetry){var n=null==(n=e.responseHeaders)?void 0:n.get("Retry-After"),n=null!=n?parseInt(n,10):void 0;if(null!=n&&Number.isInteger(n)&&!(n<0)){var r,n=1e3*n;if("function"!=typeof i.retryRateLimitedRequests||i.retryRateLimitedRequests(n))return r=f("./util").delay,await r(n),u.request.send(t)}}throw e}}),u.request=c,u.pine=e,u.errors=a,u.version=n,u},t.setSharedOptions=function(e){r.globalEnv[o]&&console.error("Shared SDK options have already been used. You may have a race condition in your code."),r.globalEnv[a]&&console.error("Shared SDK options have already been set. You may have a race condition in your code."),r.globalEnv[i]=e,r.globalEnv[a]=!0};t.fromSharedOptions=function(){var e=r.globalEnv[i];return r.globalEnv[o]=!0,(0,t.getSdk)(e)}},{"./auth":2,"./logs":4,"./models":17,"./pine":27,"./settings":28,"./types/auth":29,"./types/contract":30,"./types/jwt":33,"./types/models":34,"./types/user-invite":35,"./util":47,"./util/global-env":46,"./util/pubsub":49,"./util/sdk-version":51,"./util/settings-client":53,"balena-auth":57,"balena-errors":60,"balena-request":67,"p-throttle":452,tslib:564}],4:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let s=e("events"),l=e("ndjson");var r=e("./util/global-env");let c=("AbortController"in r.globalEnv?r.globalEnv:e("abortcontroller-polyfill/dist/cjs-ponyfill")).AbortController;n.default=function({request:o,sdkInstance:n},a){return{async subscribe(e,i){if(null!=i&&"start"in i&&null!=i.start&&null==i.count)throw new Error("The count parameter is required when specifying the start parameter");e=await n.models.device.get(e,{$select:"uuid"});{null==i&&(i={});let t=new s.EventEmitter,n=new c,r=(0,l.parse)({strict:!0===a.debug});return o.stream({url:`/device/v2/${e.uuid}/logs`,qs:Object.assign(Object.assign({},i),{stream:1}),baseUrl:a.apiUrl,signal:n.signal}).then(function(e){return e.on("error",e=>{r.emit("error",e)}),r.on("data",function(e){n.signal.aborted||t.emit("line",e)}),r.on("error",function(e){n.signal.aborted||t.emit("error",e)}),e.pipe(r)}).catch(function(e){n.signal.aborted||t.emit("error",e)}),t.unsubscribe=function(){n.abort(),r.destroy()},t}},async history(e,t){return(async(e,t)=>e=(await o.send({url:`/device/v2/${e.uuid}/logs`,qs:null!=t?t:{},baseUrl:a.apiUrl})).body)(await n.models.device.get(e,{$select:"uuid"}),t)}}}},{"./util/global-env":46,"abortcontroller-polyfill/dist/cjs-ponyfill":54,events:178,ndjson:432}],5:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let s=e("tslib").__importStar(e("balena-errors")),l=e("../util");n.default=function({pine:n,request:i,sdkInstance:r},{apiUrl:o}){let a={async create({name:e,expiryDate:t,description:n=null}){if(void 0===t)throw new s.BalenaInvalidParameterError("createApiKeyParams.expiryDate",t);e={name:e,expiryDate:t};"string"==typeof n&&n&&(e.description=n);try{var r=(await i.send({method:"POST",url:"/api-key/user/full",baseUrl:o,body:e})).body;return r}catch(e){throw new s.BalenaNotLoggedIn}},async getAll(e={}){return n.get({resource:"api_key",options:(0,l.mergePineOptions)({$orderby:"name asc"},e)})},async getAllNamedUserApiKeys(e={}){return a.getAll((0,l.mergePineOptions)({$filter:{is_of__actor:await r.auth.getActorId(),name:{$ne:null}}},e))},async getProvisioningApiKeysByApplication(e,t={}){e=(await r.models.application.get(e,{$select:"actor"})).actor;return a.getAll((0,l.mergePineOptions)({$filter:{is_of__actor:e.__id}},t))},async getDeviceApiKeysByDevice(e,t={}){e=(await r.models.device.get(e,{$select:"actor"})).actor;return n.get({resource:"api_key",options:(0,l.mergePineOptions)({$filter:{is_of__actor:e.__id},$orderby:"name asc"},t)})},async update(e,t){if(!t)throw new s.BalenaInvalidParameterError("apiKeyInfo",t);if(null===t.name||""===t.name)throw new s.BalenaInvalidParameterError("apiKeyInfo.name",t.name);await n.patch({resource:"api_key",id:e,body:{name:t.name,description:t.description,expiry_date:t.expiryDate}})},async revoke(e){await n.delete({resource:"api_key",id:e})}};return a}},{"../util":47,"balena-errors":60,tslib:564}],6:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let s=e("tslib").__importStar(e("balena-errors")),l=e("../util"),c="invitee__is_invited_to__application";n.default=function(e,t,o){let{request:n,pine:a}=e,r=t.apiUrl,i={getAll(e={}){return a.get({resource:c,options:e})},async getAllByApplication(e,t={}){e=(await o(e,{$select:"id"})).id;return i.getAll((0,l.mergePineOptions)({$filter:{is_invited_to__application:e}},t))},async create(e,{invitee:t,roleName:n,message:r}){var[{id:e},i]=await Promise.all([o(e,{$select:"id"}),n?a.get({resource:"application_membership_role",options:{$top:1,$select:"id",$filter:{name:n}}}):void 0]),t={invitee:t,is_invited_to__application:e,message:r};if(i){r=null==(e=i[0])?void 0:e.id;if(!r&&n)throw new s.BalenaApplicationMembershipRoleNotFound(n);t.application_membership_role=r}return a.post({resource:c,body:t})},async revoke(e){await a.delete({resource:c,id:e})},async accept(e){try{await n.send({method:"POST",url:"/user/v1/invitation/"+e,baseUrl:r})}catch(e){if(401===e.statusCode)throw new s.BalenaNotLoggedIn;throw e}}};return i}},{"../util":47,"balena-errors":60,tslib:564}],7:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let r=e("tslib").__importStar(e("balena-errors")),i=e("../util"),l="user_application_membership";n.default=function(e,o){let a=e.pine,s=async e=>{var t=await a.get({resource:"application_membership_role",id:{name:e},options:{$select:"id"}});if(t)return t.id;throw new r.BalenaApplicationMembershipRoleNotFound(e)};return{async get(e,t={}){if("number"!=typeof e&&"object"!=typeof e)throw new r.BalenaInvalidParameterError("membershipId",e);t=await a.get({resource:l,id:e,options:t});if(null==t)throw new r.BalenaError("Application Membership not found: "+e);return t},async getAllByApplication(e,t={}){e=(await o(e,{$select:"id"})).id;return a.get({resource:l,options:(0,i.mergePineOptions)({$filter:{is_member_of__application:e}},t)})},async getAllByUser(e,t={}){if("number"!=typeof e&&"string"!=typeof e)throw new r.BalenaInvalidParameterError("usernameOrId",e);return a.get({resource:l,options:(0,i.mergePineOptions)({$filter:{user:"number"==typeof e?e:{$any:{$alias:"u",$expr:{u:{username:e}}}}}},t)})},async create({application:e,username:t,roleName:n}){var[{id:e,organization:r},i]=await Promise.all([o(e,{$select:"id",$expand:{organization:{$select:"id",$expand:{organization_membership:{$select:"id",$filter:{user:{username:t}}}}}}}),n?s(n):void 0]);if(0===r[0].organization_membership.length)throw new Error("It is necessary that each user (Auth) that is member of an application that has an organization, is member of the organization");r={username:t,is_member_of__application:e};return n&&(r.application_membership_role=i),a.post({resource:l,body:r})},async changeRole(e,t){t=await s(t);await a.patch({resource:l,id:e,body:{application_membership_role:t}})},async remove(e){await a.delete({resource:l,id:e})}}}},{"../util":47,"balena-errors":60,tslib:564}],8:[function(y,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=y("tslib");let v=n.__importStar(y("url")),b=n.__importDefault(y("lodash/once")),_=n.__importStar(y("balena-errors")),w=y("../util"),x=y("../util/device-service-details");t.default=function(e,t){let n,{request:i,pine:s,sdkInstance:l}=e,o=t.apiUrl;var r=y("./application-membership").default(e,(...e)=>g.get(...e)),e=y("./application-invite").default(e,t,(...e)=>g.get(...e)),a=y("../util/dependent-resource").buildDependentResource;let c=(0,b.default)(()=>y("../util/request-batching").batchResourceOperationFactory({getAll:g.getAll,NotFoundError:_.BalenaApplicationNotFound,AmbiguousResourceError:_.BalenaAmbiguousApplication,chunkSize:t.requestBatchingChunkSize}));var u=a({pine:s},{resourceName:"application_tag",resourceKeyField:"tag_key",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application tagsModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),p=a({pine:s},{resourceName:"application_config_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application configVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),f=a({pine:s},{resourceName:"application_environment_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application envVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),a=a({pine:s},{resourceName:"build_environment_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application buildVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}});let d=null!=(n=t.dashboardUrl)?n:o.replace(/api/,"dashboard"),h=async e=>(0,w.isId)(e)?e:(e=(await g.get(e,{$select:"id"})).id,e),m={is_directly_accessible_by__user:{$any:{$alias:"dau",$expr:{1:1}}}},g={_getId:h,getDashboardUrl(e){if("number"==typeof e&&Number.isFinite(e))return v.resolve(d,"/apps/"+e);throw new Error("The id option should be a finite number")},async getAll(e,t){return await s.get({resource:"application",options:(0,w.mergePineOptions)(Object.assign(Object.assign({},"directly_accessible"===t&&{$filter:m}),{$orderby:"app_name asc"}),null!=e?e:{})})},async getAllDirectlyAccessible(e){return g.getAll(e,"directly_accessible")},async getAllByOrganization(e,t){e=(await l.models.organization.get(e,{$select:"id"})).id;return await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:{organization:e},$orderby:"app_name asc"},null!=t?t:{})})},async get(e,t,n){null==t&&(t={});n="directly_accessible"===n?m:null;let r;if((0,w.isId)(e))r=await s.get({resource:"application",id:e,options:(0,w.mergePineOptions)(null!=n?{$filter:n}:{},t)});else if("string"==typeof e){var i=e.toLowerCase(),n=await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:Object.assign(Object.assign({},n),{$or:{slug:i,uuid:i}})},t)});if(1<n.length)throw new _.BalenaAmbiguousApplication(e);r=n[0]}if(null==r)throw new _.BalenaApplicationNotFound(e);return r},async getDirectlyAccessible(e,t){return g.get(e,t,"directly_accessible")},async getWithDeviceServiceDetails(e,t){null==t&&(t={});t=(0,w.mergePineOptions)({$expand:[{owns__device:{$expand:(0,x.getCurrentServiceDetailsPineExpand)(!0)}}]},t),e=await g.get(e,t);return e.owns__device&&(e.owns__device=e.owns__device.map(e=>(0,x.generateCurrentServiceDetails)(e))),e},async getAppByName(e,t,n){null==t&&(t={});n="directly_accessible"===n?m:null,n=await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:Object.assign(Object.assign({},n),{app_name:e})},t)});if(0===n.length)throw new _.BalenaApplicationNotFound(e);if(1<n.length)throw new _.BalenaAmbiguousApplication(e);var[t]=n;return t},has:async e=>{try{return await g.get(e,{$select:["id"]}),!0}catch(e){if(e instanceof _.BalenaApplicationNotFound)return!1;throw e}},hasAny:async()=>0!==(await g.getAll({$select:["id"]},"directly_accessible")).length,async create({name:e,uuid:t,applicationClass:n,deviceType:r,organization:i}){if(null==i)throw new _.BalenaInvalidParameterError("organization",i);var o=(async()=>(await l.models.deviceType.get(r,{$select:"id"})).id)(),a=s.get({resource:"organization",id:{[(0,w.isId)(i)?"id":"handle"]:i},options:{$select:["id"]}}).then(function(e){if(e)return e.id;throw new _.BalenaOrganizationNotFound(i)}),[o,a]=await Promise.all([o,a]),e={app_name:e,uuid:t,is_for__device_type:o};return a&&(e.organization=a),n&&(e.is_of__class=n),s.post({resource:"application",body:e})},remove:async e=>{var t;"string"==typeof e?(t=(await l.models.application.get(e,{$select:"id"})).id,await s.delete({resource:"application",id:t})):await c()({parameterName:"slugOrUuidOrIdOrIds",uuidOrIdOrArray:e,fn:async e=>{await s.delete({resource:"application",options:{$filter:{id:{$in:e.map(e=>e.id)}}}})}})},rename:async(e,t)=>{e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{app_name:t}})},restart:t=>(0,w.withSupervisorLockedError)(async()=>{var e=(await l.models.application.get(t,{$select:"id"})).id;await i.send({method:"POST",url:`/application/${e}/restart`,baseUrl:o})}),generateProvisioningKey:async({slugOrUuidOrId:e,keyExpiryDate:t,keyName:n,keyDescription:r})=>{e=(await l.models.application.get(e,{$select:"id"})).id,e=(await i.send({method:"POST",url:"/api-key/v2/",baseUrl:o,body:{actorType:"application",actorTypeId:e,roles:["provisioning-api-key"],name:n,description:r,expiryDate:t}})).body;return e},purge:e=>(0,w.withSupervisorLockedError)(async()=>{await i.send({method:"POST",url:"/supervisor/v1/purge",baseUrl:o,body:{appId:e,data:{appId:""+e}}})}),shutdown:(e,t)=>(0,w.withSupervisorLockedError)(async()=>{null==t&&(t={}),await i.send({method:"POST",url:"/supervisor/v1/shutdown",baseUrl:o,body:{appId:e,data:{force:Boolean(t.force)}}})}),reboot:(e,t)=>(0,w.withSupervisorLockedError)(async()=>{null==t&&(t={}),await i.send({method:"POST",url:"/supervisor/v1/reboot",baseUrl:o,body:{appId:e,data:{force:Boolean(t.force)}}})}),willTrackNewReleases:async e=>{e=(await g.get(e,{$select:"should_track_latest_release"})).should_track_latest_release;return e},isTrackingLatestRelease:async e=>{var e=await g.get(e,{$select:"should_track_latest_release",$expand:{should_be_running__release:{$select:"id"},owns__release:{$select:"id",$top:1,$filter:{is_final:!0,is_passing_tests:!0,is_invalidated:!1,status:"success"},$orderby:"created_at desc"}}}),t=e.should_be_running__release[0],n=e.owns__release[0];return e.should_track_latest_release&&(!n||(null==t?void 0:t.id)===n.id)},pinToRelease:async(e,t)=>{e=await h(e),t=await l.models.release.get(t,{$select:"id",$top:1,$filter:{belongs_to__application:e,status:"success"}});await s.patch({resource:"application",id:e,body:{should_be_running__release:t.id,should_track_latest_release:!1}})},getTargetReleaseHash:async e=>null==(e=(await g.get(e,{$select:"id",$expand:{should_be_running__release:{$select:"commit"}}})).should_be_running__release[0])?void 0:e.commit,trackLatestRelease:async e=>{var e=await g.get(e,{$select:"id",$expand:{owns__release:{$select:"id",$top:1,$filter:{is_final:!0,is_passing_tests:!0,is_invalidated:!1,status:"success"},$orderby:"created_at desc"}}}),t={should_track_latest_release:!0},n=e.owns__release[0];n&&(t.should_be_running__release=n.id),await s.patch({resource:"application",id:e.id,body:t})},enableDeviceUrls:async e=>{e=(await g.get(e,{$select:"id"})).id;await s.patch({resource:"device",body:{is_web_accessible:!0},options:{$filter:{belongs_to__application:e}}})},disableDeviceUrls:async e=>{e=(await g.get(e,{$select:"id"})).id;await s.patch({resource:"device",body:{is_web_accessible:!1},options:{$filter:{belongs_to__application:e}}})},async grantSupportAccess(e,t){if(null==t||t<=Date.now())throw new _.BalenaInvalidParameterError("expiryTimestamp",t);e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{is_accessible_by_support_until__date:t}})},revokeSupportAccess:async e=>{e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{is_accessible_by_support_until__date:null}})},tags:{getAllByApplication:u.getAllByParent,set:u.set,remove:u.remove},configVar:{getAllByApplication:p.getAllByParent,get:p.get,set:p.set,remove:p.remove},envVar:{getAllByApplication:f.getAllByParent,get:f.get,set:f.set,remove:f.remove},buildVar:{getAllByApplication:a.getAllByParent,get:a.get,set:a.set,remove:a.remove},membership:r,invite:e};return g}},{"../util":47,"../util/dependent-resource":39,"../util/device-service-details":44,"../util/request-batching":50,"./application-invite":6,"./application-membership":7,"balena-errors":60,"lodash/once":394,tslib:564,url:571}],9:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.aliases=n.BalenaOS=void 0,n.BalenaOS={name:"balenaOS",slug:"balenaos",type:"sw.os",description:"Balena OS",partials:{image:["{{#each deviceType.partials.instructions}}{{{this}}} {{/each}}"],internalFlash:["{{#each deviceType.partials.connectDevice}}{{{this}}} {{/each}}","Write the {{name}} file you downloaded to the {{deviceType.name}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","{{#each deviceType.partials.disconnectDevice}}{{{this}}} {{/each}}","{{{deviceType.partials.bootDevice}}} to boot the device."],externalFlash:["{{#each deviceType.partials.instructions}}{{{this}}} {{/each}}","Insert the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} to the host machine.","Write the {{name}} file you downloaded to the {{resolveContractAlias deviceType.data.media.altBoot.[0]}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","Remove the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} from the host machine.","Insert the freshly flashed {{resolveContractAlias deviceType.data.media.altBoot.[0]}} into the {{deviceType.name}}.",'<strong role="alert">Warning!</strong> This will also completely erase internal storage medium, so please make a backup first.',"{{#each deviceType.partials.bootDeviceExternal}}{{{this}}} {{/each}}","Wait for the {{deviceType.name}} to finish flashing and shutdown. {{#if deviceType.partials.flashIndicator}}Please wait until {{deviceType.partials.flashIndicator}}.{{/if}}","Remove the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} from the {{deviceType.name}}.","{{#each deviceType.partials.bootDeviceInternal}}{{{this}}} {{/each}}","{{{deviceType.partials.bootDevice}}} to boot the device."],externalBoot:["Insert the {{resolveContractAlias deviceType.data.media.defaultBoot}} to the host machine.","Write the {{name}} file you downloaded to the {{resolveContractAlias deviceType.data.media.defaultBoot}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","Remove the {{resolveContractAlias deviceType.data.media.defaultBoot}} from the host machine.","Insert the freshly flashed {{resolveContractAlias deviceType.data.media.defaultBoot}} into the {{deviceType.name}}.","{{{deviceType.partials.bootDevice}}} to boot the device."],jetsonFlash:["To provision {{deviceType.name}}, follow the instructions using our [Jetson Flash tool](https://github.com/balena-os/jetson-flash/blob/master/docs/{{deviceType.slug}}.md) to make the process more streamlined."],usbMassStorage:[`{{#each deviceType.partials.instructions}}{{{this}}}
{{/each}}`],edisonFlash:{Linux:["{{#each deviceType.partials.Linux.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.Linux.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."],MacOS:["{{#each deviceType.partials.MacOS.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.MacOS.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."],Windows:["{{#each deviceType.partials.Windows.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.Windows.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."]}}},n.aliases={sdcard:"SD card",usb_mass_storage:"USB key"}},{}],10:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let a=e("tslib");n.default=function({request:r,sdkInstance:t},{apiUrl:i,isBrowser:n}){let o=async e=>{e=(await t.models.organization.get(e,{$select:"id"})).id;return e};return{getAccount:async e=>{e=await o(e),e=(await r.send({method:"GET",url:"/billing/v1/account/"+e,baseUrl:i})).body;return e},getPlan:async e=>{e=await o(e),e=(await r.send({method:"GET",url:`/billing/v1/account/${e}/plan`,baseUrl:i})).body;return e},getBillingInfo:async e=>{e=await o(e),e=(await r.send({method:"GET",url:`/billing/v1/account/${e}/info`,baseUrl:i})).body;return e},createSetupIntent:async e=>{var t=e.organization,e=a.__rest(e,["organization"]),t=await o(t),t=(await r.send({method:"POST",url:`/billing/v1/account/${t}/setup-intent`,baseUrl:i,body:e})).body;return t},updateBillingInfo:async(e,t)=>{e=await o(e),e=(await r.send({method:"PATCH",url:`/billing/v1/account/${e}/info`,baseUrl:i,body:t})).body;return e},removeBillingInfo:async e=>{e=await o(e),e=(await r.send({method:"DELETE",url:`/billing/v1/account/${e}/info`,baseUrl:i})).body;return e},updateAccountInfo:async(e,t)=>{e=await o(e);await r.send({method:"PATCH",url:"/billing/v1/account/"+e,baseUrl:i,body:t})},changePlan:async(e,t)=>{var n=t.cycle,t=a.__rest(t,["cycle"]),e=await o(e);await r.send({method:"PATCH",url:`/billing/v1/account/${e}/plan`,baseUrl:i,body:Object.assign({annual:"annual"===n},t)})},getInvoices:async e=>{e=await o(e),e=(await r.send({method:"GET",url:`/billing/v1/account/${e}/invoices`,baseUrl:i})).body;return e},async downloadInvoice(e,t){e=`/billing/v1/account/${await o(e)}/invoices/${t}/download`;return n?(t=(await r.send({method:"GET",url:e,baseUrl:i,responseFormat:"blob"})).body,t):r.stream({method:"GET",url:e,baseUrl:i})}}}},{tslib:564}],11:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("tslib");let o=r.__importStar(e("balena-errors")),a=r.__importDefault(e("lodash/union"));n.default=function(e,t){let n=e.request,r=t.apiUrl,i={getAll:async()=>{var e=(await n.send({method:"GET",url:"/config",baseUrl:r,sendToken:!1})).body;return"deviceTypes"in e&&delete e.deviceTypes,e},getDeviceTypes:async()=>{var e=(await n.send({method:"GET",url:"/device-types/v1",baseUrl:r})).body;if(null==e)throw new Error("No device types");return e.map(function(e){return delete e.instructions,e})},getDeviceTypeManifestBySlug:async t=>{var e=(await i.getDeviceTypes()).find(e=>e.name===t||e.slug===t||(null==(e=e.aliases)?void 0:e.includes(t)));if(null==e)throw new o.BalenaInvalidDeviceType(t);return e},getDeviceOptions:async e=>{var e=await i.getDeviceTypeManifestBySlug(e);return(0,a.default)(e.options,null==(e=e.initialization)?void 0:e.options)},getConfigVarSchema:async e=>{e=(await n.send({method:"GET",url:"/config/vars"+("string"==typeof e?"?deviceType="+e:""),baseUrl:r,sendToken:"string"==typeof e})).body;return e}};return i}},{"balena-errors":60,"lodash/union":400,tslib:564}],12:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});let o=e("../util");n.default=function({pine:r,sdkInstance:t}){let i=async e=>{e=(await t.models.organization.get(e,{$select:"id"})).id;return e};return{getAllByOrg:async(e,t)=>{e=await i(e);return await r.get({resource:"credit_bundle",options:(0,o.mergePineOptions)(null!=t?t:{},{$filter:{belongs_to__organization:e},$orderby:{created_at:"desc"}})})},create:async(e,t,n)=>{e=await i(e);return r.post({resource:"credit_bundle",body:{belongs_to__organization:e,is_for__feature:t,original_quantity:n}})}}}},{"../util":47}],13:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r=e("tslib");let o=e("../util"),a=r.__importStar(e("balena-errors")),s=r.__importStar(e("handlebars")),l=r.__importDefault(e("lodash/cloneDeep")),c=e("./balenaos-contract"),u={helpers:{resolveContractAlias:e=>{var t;return null!=(t=c.aliases[e])?t:e}}},p=(e,t,n)=>{let r=Object.assign({},t);for(var i of Object.keys(e)){var o=e[i];if(Array.isArray(o)){let e=r;for(var a of n)e=e[a];e[i]=o.flatMap(e=>s.compile(e)(r,u).split(`
`)).map(e=>e.trim()).filter(e=>e)}else r=p(o,r,n.concat([i]))}return r},f=e=>e.partials?p(e.partials,e,["partials"]):e,d=e=>{var t=null==(t=e.data)?void 0:t.flashProtocol,n=null==(n=null==(n=e.data)?void 0:n.media)?void 0:n.defaultBoot;if(t)return"RPIBOOT"===t?"internalFlash":t;if(n)return"image"===n?"image":"internal"===n?"externalFlash":"externalBoot";throw new a.BalenaError("Unable to determine installation method for contract: "+e.slug)};n.default=function(e){let r=e.pine,i={async get(e,t){if(null!=t||(t={}),null==e)throw new a.BalenaInvalidDeviceType(e);let n;if(null==(n="string"==typeof e?(await i.getAll((0,o.mergePineOptions)({$top:1,$filter:{device_type_alias:{$any:{$alias:"dta",$expr:{dta:{is_referenced_by__alias:e}}}}}},t)))[0]:await r.get({resource:"device_type",id:e,options:t})))throw new a.BalenaInvalidDeviceType(e.toString());return n},async getAll(e){return null==e&&(e={}),await r.get({resource:"device_type",options:(0,o.mergePineOptions)({$orderby:"name asc"},e)})},async getAllSupported(e){return null==e&&(e={}),await i.getAll((0,o.mergePineOptions)({$filter:{is_default_for__application:{$any:{$alias:"idfa",$expr:{idfa:{is_host:!0,is_archived:!1,owns__release:{$any:{$alias:"r",$expr:{r:{status:"success",is_final:!0,is_invalidated:!1}}}}}}}}}},e))},getBySlugOrName:async(e,t)=>{null==t&&(t={});var[t]=await i.getAll((0,o.mergePineOptions)({$top:1,$filter:{$or:{name:e,slug:e}}},t));if(null==t)throw new a.BalenaInvalidDeviceType(e);return t},getName:async e=>(await i.getBySlugOrName(e,{$select:"name"})).name,getSlugByName:async e=>(await i.getBySlugOrName(e,{$select:"slug"})).slug,getInterpolatedPartials:async e=>{var t=(await i.getBySlugOrName(e,{$select:"contract"})).contract;if(t)return f(t);throw new Error("Could not find contract for device type "+e)},getInstructions:async e=>{let t;if("string"==typeof e){if({contract:t}=await i.getBySlugOrName(e,{$select:"contract"}),null==t||!t.partials)throw new Error("Instruction partials not defined for "+e)}else t=e;return e=t,n=d(e),e={deviceType:f(e)},null==(e=f(Object.assign(Object.assign({},(0,l.default)(c.BalenaOS)),e)).partials)?void 0:e[n];var n},getInstallMethod:async e=>{e=(await i.getBySlugOrName(e,{$select:"contract"})).contract;return e?d(e):null}};return i}},{"../util":47,"./balenaos-contract":9,"balena-errors":60,handlebars:197,"lodash/cloneDeep":373,tslib:564}],14:[function(S,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.DeviceState=void 0;let O=S("tslib"),E=S("../types/device-overall-status"),j=O.__importStar(S("url")),A=O.__importDefault(S("lodash/once")),k=O.__importStar(S("balena-semver")),P=O.__importStar(S("balena-errors")),I=O.__importDefault(S("memoizee")),T=S("../util"),R=S("../util/device-os-version"),$=S("../util/device-service-details"),M=S("../util/local-mode"),C=S("./device.supervisor-api.partial"),L=S("date-fns/subDays"),N="RESIN_OVERRIDE_LOCK";t.DeviceState=O.__importStar(S("../types/device-state"));t.default=function(e,t){let n,{pine:s,request:i,sdkInstance:p}=e,{apiUrl:a,deviceUrlsBase:r}=t,l=(0,A.default)(()=>S("balena-register-device").getRegisterDevice({request:i}));var o=S("../util/dependent-resource").buildDependentResource;let c=(0,A.default)(()=>S("../util/device-actions/os-update/utils").hupActionHelper),u=(0,A.default)(()=>S("../util/date")),f=(0,A.default)(()=>S("../util/request-batching").batchResourceOperationFactory({getAll:w,NotFoundError:P.BalenaDeviceNotFound,AmbiguousResourceError:P.BalenaAmbiguousDevice,chunkSize:t.requestBatchingChunkSize})),d=(0,A.default)(async()=>{var e=await v();return(0,S("../util/device-actions/os-update").getOsUpdateHelper)(e,i)}),h=o({pine:s},{resourceName:"device_tag",resourceKeyField:"tag_key",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device tagsModel getResourceId: "+typeof e);e=(await x.get(e,{$select:"id"})).id;return e}}),m=o({pine:s},{resourceName:"device_config_variable",resourceKeyField:"name",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device configVarModel getResourceId: "+typeof e);e=(await x.get(e,{$select:"id"})).id;return e}}),g=o({pine:s},{resourceName:"device_environment_variable",resourceKeyField:"name",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device envVarModel getResourceId: "+typeof e);e=(await x.get(e,{$select:"id"})).id;return e}}),y=null!=(n=t.dashboardUrl)?n:a.replace(/api/,"dashboard"),v=(0,A.default)(async function(){return null!=r?r:(await p.models.config.getAll()).deviceUrlsBase}),b=async(e,t)=>{await f()({uuidOrIdOrArray:e,fn:async e=>{await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:t})}})},_=(e,t)=>{let n,r;if(null!=e){if(!(e instanceof Date))throw new P.BalenaInvalidParameterError("fromDate",e);n={$ge:e}}if(null!=t){if(!(t instanceof Date))throw new P.BalenaInvalidParameterError("toDate",t);r={$le:t}}return n||r?{created_at:Object.assign(Object.assign({},n),r)}:{}};async function w(e){return null==e&&(e={}),await s.get({resource:"device",options:(0,T.mergePineOptions)({$orderby:"device_name asc"},e)})}let x=Object.assign(Object.assign({OverallStatus:E.DeviceOverallStatus,getDashboardUrl(e){if("string"!=typeof e||0===e.length)throw new Error("The uuid option should be a non empty string");return j.resolve(y,`/devices/${e}/summary`)},async getAllByApplication(e,t){null==t&&(t={});e=(await p.models.application.get(e,{$select:"id"})).id;return w((0,T.mergePineOptions)({$filter:{belongs_to__application:e}},t))},async getAllByOrganization(e,t){null==t&&(t={});e=(await p.models.organization.get(e,{$select:"id"})).id;return w((0,T.mergePineOptions)({$filter:{belongs_to__application:{$any:{$alias:"bta",$expr:{bta:{organization:e}}}}}},t))},async get(e,t){if(null!=t||(t={}),null==e)throw new P.BalenaDeviceNotFound(e);if(""===e)throw new P.BalenaInvalidParameterError("uuidOrId",e);let n;var r=(0,T.isFullUuid)(e);if(r||(0,T.isId)(e))n=await s.get({resource:"device",id:r?{uuid:e}:e,options:t});else{r=await s.get({resource:"device",options:(0,T.mergePineOptions)({$filter:{uuid:{$startswith:e}}},t)});if(1<r.length)throw new P.BalenaAmbiguousDevice(e);n=r[0]}if(null==n)throw new P.BalenaDeviceNotFound(e);return n},async getWithServiceDetails(e,t){null==t&&(t={});e=await x.get(e,(0,T.mergePineOptions)({$expand:(0,$.getCurrentServiceDetailsPineExpand)(!0)},t));return(0,$.generateCurrentServiceDetails)(e)},async getByName(e,t){null==t&&(t={});t=await w((0,T.mergePineOptions)({$filter:{device_name:e}},t));if(0===t.length)throw new P.BalenaDeviceNotFound(e);return t},getName:async e=>{e=(await x.get(e,{$select:"device_name"})).device_name;return e},getApplicationName:async e=>(await x.get(e,{$select:"id",$expand:{belongs_to__application:{$select:"app_name"}}})).belongs_to__application[0].app_name,has:async e=>{try{return await x.get(e,{$select:["id"]}),!0}catch(e){if(e instanceof P.BalenaDeviceNotFound)return!1;throw e}},isOnline:async e=>{e=(await x.get(e,{$select:"is_online"})).is_online;return e},getLocalIPAddresses:async e=>{var{is_online:t,ip_address:n}=await x.get(e,{$select:["is_online","ip_address"]});if(t)return(null!=n?n:"").split(" ");throw new Error("The device is offline: "+e)},getMACAddresses:async e=>{e=(await x.get(e,{$select:["mac_address"]})).mac_address;return null==e?[]:e.split(" ")},getMetrics:async e=>await x.get(e,{$select:["memory_usage","memory_total","storage_block_device","storage_usage","storage_total","cpu_usage","cpu_temp","cpu_id","is_undervolted"]}),remove:async e=>{await f()({uuidOrIdOrArray:e,fn:async e=>{await s.delete({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}}})}})},deactivate:async e=>{await b(e,{is_active:!1})},rename:async(e,t)=>{await b(e,{device_name:t})},setNote:async(e,t)=>{await b(e,{note:t})},setCustomLocation:async(e,t)=>{await b(e,{custom_latitude:String(t.latitude),custom_longitude:String(t.longitude)})},unsetCustomLocation:async e=>{await x.setCustomLocation(e,{latitude:"",longitude:""})},move:async(e,n)=>{let r=await p.models.application.get(n,{$select:"id",$expand:{is_for__device_type:{$select:"is_of__cpu_architecture",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}}),i=r.is_for__device_type[0].is_of__cpu_architecture[0].slug;await f()({uuidOrIdOrArray:e,options:{$select:"is_of__device_type",$expand:{is_of__device_type:{$select:"is_of__cpu_architecture",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}},groupByNavigationPoperty:"belongs_to__application",fn:async e=>{for(var t of e)if(!p.models.os.isArchitectureCompatibleWith(t.is_of__device_type[0].is_of__cpu_architecture[0].slug,i))throw new P.BalenaInvalidDeviceType("Incompatible application: "+n);await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:{belongs_to__application:r.id}})}})}},(0,C.getSupervisorApiHelper)(e,t)),{getSupervisorTargetState:async(e,t=2)=>{e=(await x.get(e,{$select:"uuid"})).uuid,t=(await i.send({url:`/device/v${t}/${e}/state`,baseUrl:a})).body;return t},getSupervisorTargetStateForApp:async(e,t)=>{e=(await p.models.application.get(e,{$select:"uuid"})).uuid,e=(await i.send({url:`/device/v3/fleet/${e}/state/?releaseUuid=`+(null!=t?t:""),baseUrl:a})).body;return e},generateUniqueKey(){return l().generateUniqueKey()},async register(e,t,n){var r={$select:"id",$expand:{is_for__device_type:{$select:"slug",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}},[{id:e},r,i,o]=await Promise.all([p.auth.getUserInfo(),p.models.application.generateProvisioningKey({slugOrUuidOrId:e,keyExpiryDate:new Date(Date.now()+6e5).toISOString(),keyDescription:"Created by SDK to register a device"}),p.models.application.get(e,r),"string"==typeof n?p.models.deviceType.get(n,{$select:"slug",$expand:{is_of__cpu_architecture:{$select:"slug"}}}):null]);if(null!=o&&!p.models.os.isArchitectureCompatibleWith(o.is_of__cpu_architecture[0].slug,i.is_for__device_type[0].is_of__cpu_architecture[0].slug))throw new P.BalenaInvalidDeviceType("Incompatible device type: "+n);return l().register({userId:e,applicationId:i.id,uuid:t,deviceType:(null!=o?o:i.is_for__device_type[0]).slug,provisioningApiKey:r,apiEndpoint:a})},generateDeviceKey:async(e,t,n,r)=>{e=(await p.models.device.get(e,{$select:"id"})).id,e=(await i.send({method:"POST",url:`/api-key/device/${e}/device-key`,baseUrl:a,body:{name:t,description:n,expiryDate:r}})).body;return e},hasDeviceUrl:async e=>{e=(await x.get(e,{$select:"is_web_accessible"})).is_web_accessible;return e},getDeviceUrl:async e=>{var{is_web_accessible:t,uuid:n}=await x.get(e,{$select:["is_web_accessible","uuid"]});if(t)return`https://${n}.`+await v();throw new Error("Device is not web accessible: "+e)},enableDeviceUrl:async e=>{await b(e,{is_web_accessible:!0})},disableDeviceUrl:async e=>{await b(e,{is_web_accessible:!1})},async enableLocalMode(e){var t=["id",...M.LOCAL_MODE_SUPPORT_PROPERTIES],e=await x.get(e,{$select:t});(0,M.checkLocalModeSupported)(e),await x.configVar.set(e.id,M.LOCAL_MODE_ENV_VAR,"1")},disableLocalMode:e=>x.configVar.set(e,M.LOCAL_MODE_ENV_VAR,"0"),isInLocalMode:async e=>"1"===await x.configVar.get(e,M.LOCAL_MODE_ENV_VAR),getLocalModeSupport:M.getLocalModeSupport,enableLockOverride:e=>m.set(e,N,"1"),disableLockOverride:e=>m.set(e,N,"0"),hasLockOverride:async e=>"1"===await(async(e,t)=>{var t={$expand:{device_config_variable:{$select:"value",$filter:{name:t}},belongs_to__application:{$select:"id",$expand:{application_config_variable:{$select:"value",$filter:{name:t}}}}}},{device_config_variable:[e],belongs_to__application:[{application_config_variable:[t]}]}=await x.get(e,t);return null==(e=null!=e?e:t)?void 0:e.value})(e,N),async getStatus(e){if("string"!=typeof e&&"number"!=typeof e)throw new P.BalenaInvalidParameterError("uuidOrId",e);e=(await x.get(e,{$select:"overall_status"})).overall_status;return e},async getProgress(e){if("string"!=typeof e&&"number"!=typeof e)throw new P.BalenaInvalidParameterError("uuidOrId",e);e=(await x.get(e,{$select:"overall_progress"})).overall_progress;return e},async grantSupportAccess(e,t){if(null==t||t<=Date.now())throw new P.BalenaInvalidParameterError("expiryTimestamp",t);await b(e,{is_accessible_by_support_until__date:t})},revokeSupportAccess:async e=>{await b(e,{is_accessible_by_support_until__date:null})},lastOnline(e){var t,n=e.last_connectivity_event;return n?(t=u().timeSince,e.is_online?`Connected (for ${t(n,!1)})`:t(n)):"Connecting..."},getOsVersion:e=>(0,R.getDeviceOsSemverWithVariant)(e),isTrackingApplicationRelease:async e=>{e=(await x.get(e,{$select:"is_pinned_on__release"})).is_pinned_on__release;return!e},getTargetReleaseHash:async e=>{var e=(await x.get(e,{$select:"id",$expand:{should_be_running__release:{$select:"commit"}}})).should_be_running__release;return null==(e=e[0])?void 0:e.commit},pinToRelease:async(e,n)=>{let r=(0,I.default)(async e=>{var t=(0,T.isId)(n)?"id":"commit";return p.models.release.get(n,{$top:1,$select:"id",$filter:{[t]:n,status:"success",belongs_to__application:e},$orderby:"created_at desc"})},{primitive:!0,promise:!0});await f()({uuidOrIdOrArray:e,groupByNavigationPoperty:"belongs_to__application",fn:async(e,t)=>{t=await r(t);await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:{is_pinned_on__release:t.id}})}})},trackApplicationRelease:async e=>{await b(e,{is_pinned_on__release:null})},setSupervisorRelease:async(e,t)=>{let n=(0,T.isId)(t)?"id":"raw_version",r=(0,I.default)(async e=>{var[e]=await p.models.os.getSupervisorReleasesForCpuArchitecture(e,{$top:1,$select:"id",$filter:{[n]:t}});if(null==e)throw new P.BalenaReleaseNotFound(t);return e},{primitive:!0,promise:!0});await f()({uuidOrIdOrArray:e,options:{$select:["id","supervisor_version","os_version"],$expand:{is_of__device_type:{$select:"is_of__cpu_architecture"}}},fn:async e=>{e.forEach(e=>{(0,R.ensureVersionCompatibility)(e.supervisor_version,C.MIN_SUPERVISOR_MC_API,"supervisor"),(0,R.ensureVersionCompatibility)(e.os_version,"2.12.0","host OS")});e=(0,T.groupByMap)(e,e=>e.is_of__device_type[0].is_of__cpu_architecture.__id);await Promise.all([...e.entries()].map(async([e,t])=>{e=await r(e);await s.patch({resource:"device",options:{$filter:{id:{$in:t.map(e=>e.id)}}},body:{should_be_managed_by__release:e.id}})}))}})},_checkOsUpdateTarget({uuid:e,is_of__device_type:t,is_online:n,os_version:r,os_variant:i},o){if(!e)throw new Error("The uuid of the device is not available");if(!n)throw new Error("The device is offline: "+e);if(!r)throw new Error("The current os version of the device is not available: "+e);t=null==(n=null==t?void 0:t[0])?void 0:n.slug;if(!t)throw new Error("The device type of the device is not available: "+e);if(void 0===i)throw new Error("The os variant of the device is not available: "+e);e=null!=(n=(0,R.getDeviceOsSemverWithVariant)({os_version:r,os_variant:i}))?n:r;c().getHUPActionType(t,e,o)},startOsUpdate:async function(e,i,o={runDetached:!0}){var t;if(!i)throw new P.BalenaInvalidParameterError("targetOsVersion",i);let a=0<(null!=(t=null==(t=k.parse(i))?void 0:t.prerelease.length)?t:0),s=(0,I.default)(async e=>p.models.deviceType.get(e,{$select:"slug"}),{primitive:!0,promise:!0}),l=(0,I.default)(async(e,t)=>p.models.os.getAvailableOsVersions(e,{includeDraft:t}),{primitive:!0,promise:!0}),c=await d(),u={};return await f()({uuidOrIdOrArray:e,options:{$select:["uuid","is_online","os_version","supervisor_version","os_variant"]},groupByNavigationPoperty:"is_of__device_type",fn:async(e,t)=>{var n,r=await s(t);for(n of e)if(x._checkOsUpdateTarget(Object.assign(Object.assign({},n),{is_of__device_type:[r]}),i),!(await l(r.slug,a)).some(e=>0===k.compare(e.raw_version,i)))throw new P.BalenaInvalidParameterError("targetOsVersion",i);await(0,T.limitedMap)(e,async e=>{u[e.uuid]=await c.startOsUpdate(e.uuid,i,!0===o.runDetached?"v2":"v1")})}}),Array.isArray(e)?u:u[e]},tags:{async getAllByApplication(e,t){null==t&&(t={});e=(await p.models.application.get(e,{$select:"id"})).id;return h.getAll((0,T.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}}},t))},getAllByDevice:h.getAllByParent,set:h.set,remove:h.remove},configVar:{getAllByDevice:m.getAllByParent,async getAllByApplication(e,t){null==t&&(t={});e=(await p.models.application.get(e,{$select:"id"})).id;return m.getAll((0,T.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}},$orderby:"name asc"},t))},get:m.get,set:m.set,remove:m.remove},envVar:{getAllByDevice:g.getAllByParent,async getAllByApplication(e,t){null==t&&(t={});e=(await p.models.application.get(e,{$select:"id"})).id;return g.getAll((0,T.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}},$orderby:"name asc"},t))},get:g.get,set:g.set,remove:g.remove},serviceVar:{async getAllByDevice(e,t){null==t&&(t={});e=(await x.get(e,{$select:"id"})).id;return s.get({resource:"device_service_environment_variable",options:(0,T.mergePineOptions)({$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e}}}}}},t)})},async getAllByApplication(e,t){null==t&&(t={});e=(await p.models.application.get(e,{$select:"id"})).id;return s.get({resource:"device_service_environment_variable",options:(0,T.mergePineOptions)({$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}}}}}},$orderby:"name asc"},t)})},async get(e,t,n){var e=(await x.get(e,{$select:"id"})).id,[e]=await s.get({resource:"device_service_environment_variable",options:{$select:"value",$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e,installs__service:"number"==typeof t?t:{$any:{$alias:"is",$expr:{is:{service_name:t}}}}}}}},name:n}}});return null==e?void 0:e.value},async set(e,t,n,r){r=String(r);let i;i=(0,T.isId)(e)?e:(0,T.isFullUuid)(e)?{$any:{$alias:"d",$expr:{d:{uuid:e}}}}:(await x.get(e,{$select:"id"})).id;var o=await s.get({resource:"service_install",options:{$select:"id",$filter:{device:i,installs__service:"number"==typeof t?t:{$any:{$alias:"s",$expr:{s:{service_name:t}}}}}}}),[a]=o;if(null==a)throw new P.BalenaServiceNotFound(t);if(1<o.length)throw new P.BalenaAmbiguousDevice(e);await s.upsert({resource:"device_service_environment_variable",id:{service_install:a.id,name:n},body:{value:r}})},async remove(e,t,n){e=(await x.get(e,{$select:"id"})).id;await s.delete({resource:"device_service_environment_variable",options:{$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e,installs__service:"number"==typeof t?t:{$any:{$alias:"is",$expr:{is:{service_name:t}}}}}}}},name:n}}})}},history:{async getAllByDevice(e,t={}){let{fromDate:n=(0,L.subDays)(new Date,7),toDate:r}=t,i=O.__rest(t,["fromDate","toDate"]),o=_(n,r);if((0,T.isId)(e))o=Object.assign(Object.assign({},o),{tracks__device:e});else{if(!(0,T.isFullUuid)(e))throw new P.BalenaInvalidParameterError("uuidOrId",e);o=Object.assign(Object.assign({},o),{uuid:e})}return s.get({resource:"device_history",options:(0,T.mergePineOptions)({$filter:o},i)})},async getAllByApplication(e,t={}){var{fromDate:n=(0,L.subDays)(new Date,7),toDate:r}=t,t=O.__rest(t,["fromDate","toDate"]),e=(await p.models.application.get(e,{$select:"id"})).id;return s.get({resource:"device_history",options:(0,T.mergePineOptions