@olenbetong/appframe-core 2.0.4 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/af.common.js +97 -197
- package/dist/esm/af.common.legacy.js +98 -191
- package/dist/esm/af.common.legacy.min.js +1 -29
- package/dist/esm/af.common.legacy.min.js.map +4 -4
- package/dist/esm/af.common.min.js +1 -29
- package/dist/esm/af.common.min.js.map +4 -4
- package/dist/iife/af.common.js +97 -195
- package/dist/iife/af.common.legacy.js +98 -191
- package/dist/iife/af.common.legacy.min.js +1 -29
- package/dist/iife/af.common.legacy.min.js.map +4 -4
- package/dist/iife/af.common.min.js +1 -29
- package/dist/iife/af.common.min.js.map +4 -4
- package/es/SessionHandler.d.ts +2 -7
- package/es/SessionHandler.js +34 -135
- package/es/UserSession.d.ts +1 -2
- package/es/UserSession.js +1 -2
- package/es/downloadRequest.js +1 -4
- package/es/expose.d.ts +1 -1
- package/es/expose.js +4 -5
- package/es/index.d.ts +3 -2
- package/es/index.js +4 -3
- package/es/localize.d.ts +14 -0
- package/es/localize.js +25 -0
- package/es/parseFunc.d.ts +1 -1
- package/es/parseFunc.js +1 -1
- package/es/requireNamespace.d.ts +1 -1
- package/es/requireNamespace.js +1 -7
- package/package.json +2 -2
- package/src/SessionHandler.ts +38 -156
- package/src/UserSession.ts +1 -2
- package/src/downloadRequest.ts +1 -4
- package/src/expose.ts +4 -5
- package/src/index.ts +3 -2
- package/src/localize.ts +29 -0
- package/src/parseFunc.ts +1 -1
- package/src/requireNamespace.ts +1 -5
- package/es/warn.d.ts +0 -1
- package/es/warn.js +0 -4
- package/src/warn.ts +0 -4
|
@@ -1,30 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
<div class="session-expired-log-in" style="margin-top: 20px;">
|
|
3
|
-
<div class="row">
|
|
4
|
-
<div class="sessionExpired">
|
|
5
|
-
<h4 class="message">Frakoblet - tidsavbrudd</h4>
|
|
6
|
-
<div class="form-group">
|
|
7
|
-
<label for="username">${m("Username")}</label>
|
|
8
|
-
<input type="text" class="form-control" id="username" autofocus>
|
|
9
|
-
</div>
|
|
10
|
-
<div class="form-group">
|
|
11
|
-
<label for="password">${m("Password")}</label>
|
|
12
|
-
<input type="password" autocomplete="password" class="form-control" id="password" >
|
|
13
|
-
</div>
|
|
14
|
-
<div class="form-group">
|
|
15
|
-
<div>
|
|
16
|
-
<button type="submit" class="btn btn-default sign-in">
|
|
17
|
-
${m("Log in")}
|
|
18
|
-
</button>
|
|
19
|
-
</div>
|
|
20
|
-
</div>
|
|
21
|
-
</div>
|
|
22
|
-
</div>
|
|
23
|
-
<div class="row">
|
|
24
|
-
<div class="" style="display:none; margin: 0px 30px;">
|
|
25
|
-
<div class="alert alert-warning" role="alert" style="margin-top:10px;"></div>
|
|
26
|
-
</div>
|
|
27
|
-
</div>
|
|
28
|
-
</div>
|
|
29
|
-
`;let o=af.userSession.login?h.messages.relog:h.messages.login,s=r.querySelector(".message"),i=r.querySelector(".alert-warning"),c=r.querySelector("input[type=text]"),u=r.querySelector(".sign-in"),a=r.querySelector("input[type=password]");if(s!==null&&c!==null&&i!==null&&c!==null&&u!==null&&a!==null){s.innerText=m(o),c.value=af.userSession.login||"",c.disabled=!!af.userSession.login,c.readOnly=!!af.userSession.login,document.body.appendChild(r);let d=async()=>{a.disabled=!0;let l=new Request("/login",{body:JSON.stringify({username:c.value,password:a.value,remember:!1}),headers:{Accept:"application/json","Content-Type":"application/json; charset=utf-8","X-Requested-With":"XMLHttpRequest"},method:"POST"});try{let g=await(await fetch(l)).json();if(g.success)document.body.removeChild(r),this.showingDialog=!1,this.eventHandler.emit("onAuthenticated"),i.parentNode&&(i.parentNode.style.display="none");else throw new Error(g.error)}catch(f){if(f&&typeof f=="object"){let g=f;a.disabled=!1,a.classList.toggle("invalid",!0),a.value="",a.focus(),i.innerText=g.message?g.message:String(g),i.parentNode&&(i.parentNode.style.display="initial")}}};u.addEventListener("click",d),a.addEventListener("keyup",l=>{l.key==="Enter"&&d()}),a.addEventListener("change",l=>{l.key==="Enter"&&d()}),c.addEventListener("keyup",l=>{l.key==="Enter"&&d()}),c.addEventListener("change",l=>{l.key==="Enter"&&d()}),a.focus()}}}attachEvent(e,n){return this.eventHandler.on(e,n)}detachEvent(e,n){return this.eventHandler.off(e,n)}},p=h;j(p,"messages",{login:"Log in",relog:"Session expired - log in"});var w=class extends p{amDesignator="a.m.";dayNames=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];dayNamesShort=["sun","mon","tue","wed","thu","fri","sat"];decimalSeparator=".";domain="OB";email;formats;groupSeparator=null;integratedSecurity=!1;isDeveloper=!1;login="";loginType;monthNames=["january","february","march","april","may","june","july","august","september","october","november","december",""];monthNamesShort=["jan","feb","mar","apr","may","jun","jul","augt","sep","oct","nov","dec",""];name;pmDesignator="p.m.";shortDateFormat="dd.MM.yyyy";culture="en-GB";uiculture="en-GB";expired=()=>null;constructor(e){super(),this.formats={},Object.assign(this,e)}};function x(t,e){return new Promise(function(n,r){try{let o=URL.createObjectURL(t),s=document.body,i=document.createElement("a");i.setAttribute("download",e),i.href=o,s.append(i),i.click(),s.removeChild(i),setTimeout(function(){URL.revokeObjectURL(o),n()},250)}catch(o){r(o)}})}async function G(t,{fileName:e,signal:n,onProgress:r}){function o(i){typeof r=="function"&&r({...i})}let s=0;o({status:"requested"});try{let i=await fetch(t);if(!i.ok||!i.body){if(i.headers.get("content-type")?.includes("application/json")){let u=await i.json();if(u.error)throw new Error(u.error)}throw new Error(`${i.status} ${i.statusText}`)}try{let u=i.body.getReader(),a=new ReadableStream({start:function(d){function l(){return u.read().then(function(f){if(f.done){d.close();return}return s+=f.value.length,o({bytesReceived:s,status:"downloading"}),d.enqueue(f.value),l()})}return l()}});i=new Response(a)}catch{console.warn("Failed to replace response stream to log download progress.")}let c=await i.blob();o({bytesReceived:s,status:"downloaded"}),await x(c,e),o({bytesReceived:s,status:"completed"})}catch(i){n?.aborted?o({status:"cancelled"}):o({error:i.message,status:"error"})}}var z=/^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;function b(t){var e=t.toString().match(z);if(e===null)throw new TypeError("Unable to parse function!");return{name:e[1],args:e[2].split(","),body:e[3]}}function T(){}T.prototype=Object.create(null);var N=T;function v(t,e){if(typeof t=="object")if(typeof e=="string"){let n=e.split(".");return v(t,n)}else if(Array.isArray(e)){let n=t;for(let r=0;r<e.length;r++)n=n[e[r]]=n[e[r]]||new N;return n}else throw new TypeError("Invalid type of parameter 'namespace'");else throw new TypeError("Invalid type of parameter 'root'")}function E(t,e){console.warn(t)}function L(t,e){if(arguments.length!==2)throw new Error("Incorrect number of arguments passed to the expose function!");if(Array.isArray(e))for(let n of e){let{name:r}=b(n);if(r)L(t,n);else throw new Error("Unable to detect name of function! Name it, or only supply one function and include name in first parameter.")}else{let n,r;if(typeof e=="function"&&(n=b(e).name),typeof t=="string"){let o=t.split(".");n||(n=o[o.length-1],o=o.slice(0,o.length-1)),r=v(window,o)}else if(n&&(typeof t=="object"||typeof t=="function"))r=t;else throw new TypeError("Invalid typeof parameter 'name', or unable to parse pValue!");y(r,n)?E([t,n].join(".")+" is already defined!"):r[n]=e}}function k(t){return[af?.article?.id||"","common",t].join(".")}var A=class{isPersisted(){return!0}getLocalStorageKey(e,n){return n?["common",e].join("."):k(e)}get(e,n,r){let o=this.getLocalStorageKey(e,r),s=localStorage.getItem(o);return s!==null?JSON.parse(s):n}set(e,n,r){localStorage.setItem(this.getLocalStorageKey(e,r),JSON.stringify(n))}remove(e,n){let r=this.getLocalStorageKey(e,n);return localStorage.getItem(r)!==null?(localStorage.removeItem(r),!0):!1}clear(){let e=k("");for(let n in localStorage)n.slice(0,e.length)===e&&localStorage.removeItem(n)}},I=new A;function R(t){return`${t||af.article.id}.${af.userSession.login}`}function ue(t,e){if(!af?.userSession)return null;let n=R(e),r=JSON.parse(localStorage.getItem(n)||"{}");return t?r[t]||null:r}function de(t,e,n){if(!af?.userSession)return;let r=R(n),o=JSON.parse(localStorage.getItem(r)||"{}");typeof e<"u"?o[t]=e:o=t,localStorage.setItem(r,JSON.stringify(o))}var me="2.0.4";export{p as SessionHandler,w as UserSession,x as downloadBlob,G as downloadRequest,L as expose,m as getLocalizedString,ue as getSettings,y as has,I as localStorage,S as mitt,de as saveSettings,me as version};
|
|
1
|
+
window.addEventListener("error",e=>{try{let t={error:e.error?.message??e.message??null,file:e.filename,line:e.lineno??0,column:e.colno??0,stack:e.error?.stack??null};fetch("/data/Logger/LogError",{body:JSON.stringify(t),headers:{Accept:"application/json","Content-Type":"application/json; charset=utf-8","X-Requested-With":"XMLHttpRequest"},method:"POST"})}catch{}});function d(e){return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map(function(o){o(r)}),(n=e.get("*"))&&n.slice().map(function(o){o(t,r)})}}}var s=class{eventHandler=d();authenticated(){this.eventHandler.emit("onAuthenticated")}async expired(t,r){let n=new Promise(a=>{let i=()=>{this.eventHandler.off("onAuthenticated",i),t?.(),a()};this.eventHandler.on("onAuthenticated",i)}),o=document.querySelector("dialog.session-expired-dialog");if(o)await n;else{o=document.createElement("dialog"),o.className="session-expired-dialog",o.style.display="flex",o.style.padding="0",o.style.left="50%",o.style.transform="translateX(-50%)";let a="/login?ReturnUrl=%2fapi/sessionexpired/remove";r!=="RequireTwoFactor"?await fetch("/logout",{method:"POST"}):a="/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove",o.innerHTML=`<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${a}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`,document.body.append(o),o.showModal(),await n,o.remove()}}attachEvent(t,r){return this.eventHandler.on(t,r)}detachEvent(t,r){return this.eventHandler.off(t,r)}};var f=class extends s{amDesignator="a.m.";dayNames=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];dayNamesShort=["sun","mon","tue","wed","thu","fri","sat"];decimalSeparator=".";domain="OB";email;formats;groupSeparator=null;integratedSecurity=!1;isDeveloper=!1;login="";loginType;monthNames=["january","february","march","april","may","june","july","august","september","october","november","december",""];monthNamesShort=["jan","feb","mar","apr","may","jun","jul","augt","sep","oct","nov","dec",""];name;pmDesignator="p.m.";shortDateFormat="dd.MM.yyyy";culture="en-GB";uiculture="en-GB";constructor(t){super(),this.formats={},Object.assign(this,t)}};function g(e,t){return new Promise(function(r,n){try{let o=URL.createObjectURL(e),a=document.body,i=document.createElement("a");i.setAttribute("download",t),i.href=o,a.append(i),i.click(),a.removeChild(i),setTimeout(function(){URL.revokeObjectURL(o),r()},250)}catch(o){n(o)}})}async function K(e,{fileName:t,signal:r,onProgress:n}){function o(i){typeof n=="function"&&n({...i})}let a=0;o({status:"requested"});try{let i=await fetch(e);if(!i.ok||!i.body){if(i.headers.get("content-type")?.includes("application/json")){let l=await i.json();if(l.error)throw new Error(l.error)}throw new Error(`${i.status} ${i.statusText}`)}try{let l=i.body.getReader(),E=new ReadableStream({start:function(w){function b(){return l.read().then(function(u){if(u.done){w.close();return}return a+=u.value.length,o({bytesReceived:a,status:"downloading"}),w.enqueue(u.value),b()})}return b()}});i=new Response(E)}catch{}let j=await i.blob();o({bytesReceived:a,status:"downloaded"}),await g(j,t),o({bytesReceived:a,status:"completed"})}catch(i){r?.aborted?o({status:"cancelled"}):o({error:i.message,status:"error"})}}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var z=/^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;function p(e){var t=e.toString().match(z);if(t===null)throw new TypeError("Unable to parse function!");return{name:t[1],args:t[2].split(","),body:t[3]}}function S(){}S.prototype=Object.create(null);var x=S;function m(e,t){if(typeof e=="object"){if(typeof t=="string"){let r=t.split(".");return m(e,r)}else if(Array.isArray(t)){let r=e;for(let n=0;n<t.length;n++)r=r[t[n]]=r[t[n]]||new x;return r}}}function v(e,t){if(arguments.length!==2)throw new Error("Incorrect number of arguments passed to the expose function!");if(Array.isArray(t))for(let r of t){let{name:n}=p(r);if(n)v(e,r);else throw new Error("Unable to detect name of function! Name it, or only supply one function and include name in first parameter.")}else{let r,n;if(typeof t=="function"&&(r=p(t).name),typeof e=="string"){let o=e.split(".");r||(r=o[o.length-1],o=o.slice(0,o.length-1)),n=m(window,o)}else if(r&&(typeof e=="object"||typeof e=="function"))n=e;else throw new TypeError("Invalid typeof parameter 'name', or unable to parse pValue!");c(n,r)?console.warn([e,r].join(".")+" is already defined!"):n[r]=t}}async function R(e){try{let t=await fetch(`/api/user/localize/new/${af.article.id}`,{body:JSON.stringify({text:e}),headers:{Accept:"application/json; */*","Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},method:"POST"});if(t.ok)return await t.json()}catch{}return e}function y(e,t){if(typeof e=="string"&&e.trim().length===0)return e;if(!(e===void 0||e===""||e===null))if(af?.article?.i18n!==void 0){if(!c(af.article.i18n,e)){af.article.i18n[e]=e;let r=R(e).then(n=>(af.article.i18n[e]=n,n));if(t)return r}return af.article.i18n[e]}else return e}function N(e,...t){if(!Array.isArray(e)||e?.length||e.length!==t.length+1)throw TypeError("Method 'localize' must be used as a tag function");let r=e.map((o,a)=>a===e.length-1?o:`${o}$${a}`).join(""),n=y(r);return t.forEach((o,a)=>{n=n.replace("$"+a,o)}),n}function A(e){return[af?.article?.id||"","common",e].join(".")}var h=class{isPersisted(){return!0}getLocalStorageKey(t,r){return r?["common",t].join("."):A(t)}get(t,r,n){let o=this.getLocalStorageKey(t,n),a=localStorage.getItem(o);return a!==null?JSON.parse(a):r}set(t,r,n){localStorage.setItem(this.getLocalStorageKey(t,n),JSON.stringify(r))}remove(t,r){let n=this.getLocalStorageKey(t,r);return localStorage.getItem(n)!==null?(localStorage.removeItem(n),!0):!1}clear(){let t=A("");for(let r in localStorage)r.slice(0,t.length)===t&&localStorage.removeItem(r)}},T=new h;function L(e){return`${e||af.article.id}.${af.userSession.login}`}function re(e,t){if(!af?.userSession)return null;let r=L(t),n=JSON.parse(localStorage.getItem(r)||"{}");return e?n[e]||null:n}function ne(e,t,r){if(!af?.userSession)return;let n=L(r),o=JSON.parse(localStorage.getItem(n)||"{}");typeof t<"u"?o[e]=t:o=e,localStorage.setItem(n,JSON.stringify(o))}var se="2.1.0";export{s as SessionHandler,f as UserSession,g as downloadBlob,K as downloadRequest,v as expose,y as getLocalizedString,re as getSettings,c as has,T as localStorage,N as localize,d as mitt,ne as saveSettings,se as version};
|
|
30
2
|
//# sourceMappingURL=af.common.min.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/errorHandler.ts", "../../../../node_modules/mitt/src/index.ts", "../../src/
|
|
4
|
-
"sourcesContent": ["window.addEventListener(\"error\", (event) => {\n try {\n // Try to avoid error-logging-loop\n const data = {\n error: event.error?.message ?? event.message ?? null,\n file: event.filename,\n line: event.lineno ?? 0,\n column: event.colno ?? 0,\n stack: event.error?.stack ?? null,\n };\n\n fetch(\"/data/Logger/LogError\", {\n body: JSON.stringify(data),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n method: \"POST\",\n });\n } catch (ex) {\n // ignore\n }\n});\n", "export type EventType = string | symbol;\n\n// An event handler can take an optional event argument\n// and should not return a value\nexport type Handler<T = unknown> = (event: T) => void;\nexport type WildcardHandler<T = Record<string, unknown>> = (\n\ttype: keyof T,\n\tevent: T[keyof T]\n) => void;\n\n// An array of all currently registered event handlers for a type\nexport type EventHandlerList<T = unknown> = Array<Handler<T>>;\nexport type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;\n\n// A map of event types and their corresponding event handlers.\nexport type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<\n\tkeyof Events | '*',\n\tEventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>\n>;\n\nexport interface Emitter<Events extends Record<EventType, unknown>> {\n\tall: EventHandlerMap<Events>;\n\n\ton<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;\n\ton(type: '*', handler: WildcardHandler<Events>): void;\n\n\toff<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;\n\toff(type: '*', handler: WildcardHandler<Events>): void;\n\n\temit<Key extends keyof Events>(type: Key, event: Events[Key]): void;\n\temit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;\n}\n\n/**\n * Mitt: Tiny (~200b) functional event emitter / pubsub.\n * @name mitt\n * @returns {Mitt}\n */\nexport default function mitt<Events extends Record<EventType, unknown>>(\n\tall?: EventHandlerMap<Events>\n): Emitter<Events> {\n\ttype GenericEventHandler =\n\t\t| Handler<Events[keyof Events]>\n\t\t| WildcardHandler<Events>;\n\tall = all || new Map();\n\n\treturn {\n\n\t\t/**\n\t\t * A Map of event names to registered handler functions.\n\t\t */\n\t\tall,\n\n\t\t/**\n\t\t * Register an event handler for the given type.\n\t\t * @param {string|symbol} type Type of event to listen for, or `'*'` for all events\n\t\t * @param {Function} handler Function to call in response to given event\n\t\t * @memberOf mitt\n\t\t */\n\t\ton<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {\n\t\t\tconst handlers: Array<GenericEventHandler> | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\thandlers.push(handler);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tall!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Remove an event handler for the given type.\n\t\t * If `handler` is omitted, all handlers of the given type are removed.\n\t\t * @param {string|symbol} type Type of event to unregister `handler` from, or `'*'`\n\t\t * @param {Function} [handler] Handler function to remove\n\t\t * @memberOf mitt\n\t\t */\n\t\toff<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {\n\t\t\tconst handlers: Array<GenericEventHandler> | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\tif (handler) {\n\t\t\t\t\thandlers.splice(handlers.indexOf(handler) >>> 0, 1);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tall!.set(type, []);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Invoke all handlers for the given type.\n\t\t * If present, `'*'` handlers are invoked after type-matched handlers.\n\t\t *\n\t\t * Note: Manually firing '*' handlers is not supported.\n\t\t *\n\t\t * @param {string|symbol} type The event type to invoke\n\t\t * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler\n\t\t * @memberOf mitt\n\t\t */\n\t\temit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {\n\t\t\tlet handlers = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as EventHandlerList<Events[keyof Events]>)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(evt!);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\thandlers = all!.get('*');\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as WildCardEventHandlerList<Events>)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(type, evt!);\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n", "export function has(\n obj: any,\n key: string | number | symbol\n): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n", "import { has } from \"./has\";\n\nasync function fetchLocalizedString(text: string) {\n try {\n let response = await fetch(`/api/user/localize/new/${af.article.id}`, {\n body: JSON.stringify({ text }),\n headers: {\n Accept: \"application/json; */*\",\n \"Content-Type\": \"application/json\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n method: \"POST\",\n });\n\n if (response.ok) {\n return (await response.json()) as string;\n }\n } catch (error) {}\n\n return text;\n}\nexport function getLocalizedStringAsync(string: undefined | null): undefined | null;\nexport function getLocalizedStringAsync(string: string): Promise<string>;\nexport function getLocalizedStringAsync(string: string | undefined | null) {\n if (!string) return string;\n\n return getLocalizedString(string, true);\n}\n\nexport function getLocalizedString(string: undefined | null): undefined | null;\nexport function getLocalizedString(string: string): string;\nexport function getLocalizedString(string: string, wait: false): string;\nexport function getLocalizedString(string: string, wait: true): Promise<string>;\nexport function getLocalizedString(string: undefined | null, wait: true): undefined | null;\nexport function getLocalizedString(\n string: string | undefined | null,\n wait?: boolean\n): string | undefined | null | Promise<string> {\n if (typeof string === \"string\" && string.trim().length === 0) {\n return string;\n }\n\n if (string === undefined || string === \"\" || string === null) {\n return;\n }\n\n if (af?.article?.i18n !== undefined) {\n if (!has(af.article.i18n, string)) {\n af.article.i18n[string] = string;\n\n let promise = fetchLocalizedString(string).then((text) => {\n af.article.i18n[string] = text;\n return text;\n });\n\n if (wait) {\n return promise;\n }\n }\n\n return af.article.i18n[string];\n } else {\n return string;\n }\n}\n", "import mitt, { Emitter, Handler } from \"mitt\";\nimport { getLocalizedString } from \"./getLocalizedString.js\";\n\ntype SessionHandlerEvent = \"onExpired\" | \"onAuthenticated\";\n\nexport default class SessionHandler {\n static messages = {\n login: \"Log in\",\n relog: \"Session expired - log in\"\n };\n\n private eventHandler: Emitter<{ onAuthenticated: void; onExpired: void }> = mitt();\n private showingDialog = false;\n private dialog = null;\n\n expired(callback: Function) {\n af.userSession = af.userSession || {\n login: null\n };\n\n if (typeof callback !== \"function\") {\n throw new TypeError(\"Parameter pCallback passed to the expired function must be a function!\");\n }\n\n const once = () => {\n this.detachEvent(\"onAuthenticated\", once);\n callback();\n };\n\n this.attachEvent(\"onAuthenticated\", once);\n\n if (this.showingDialog !== true) {\n this.showingDialog = true;\n const contentContainer = document.createElement(\"div\");\n contentContainer.className = \"session-expired-container\";\n contentContainer.innerHTML = `\n<div class=\"session-expired-log-in\" style=\"margin-top: 20px;\">\n <div class=\"row\">\n <div class=\"sessionExpired\">\n <h4 class=\"message\">Frakoblet - tidsavbrudd</h4>\n <div class=\"form-group\">\n <label for=\"username\">${getLocalizedString(\"Username\")}</label>\n <input type=\"text\" class=\"form-control\" id=\"username\" autofocus>\n </div>\n <div class=\"form-group\">\n <label for=\"password\">${getLocalizedString(\"Password\")}</label>\n <input type=\"password\" autocomplete=\"password\" class=\"form-control\" id=\"password\" >\n </div>\n <div class=\"form-group\">\n <div>\n <button type=\"submit\" class=\"btn btn-default sign-in\">\n ${getLocalizedString(\"Log in\")}\n </button>\n </div>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"\" style=\"display:none; margin: 0px 30px;\">\n <div class=\"alert alert-warning\" role=\"alert\" style=\"margin-top:10px;\"></div> \n </div>\n </div>\n</div>\n`;\n const message = af.userSession.login ? SessionHandler.messages.relog : SessionHandler.messages.login;\n\n const messageElem = contentContainer.querySelector(\".message\") as HTMLHeadingElement;\n const statusElem = contentContainer.querySelector(\".alert-warning\") as HTMLDivElement;\n const userElem = contentContainer.querySelector(\"input[type=text]\") as HTMLInputElement;\n const signInElem = contentContainer.querySelector(\".sign-in\") as HTMLButtonElement;\n const passwordElem = contentContainer.querySelector(\"input[type=password]\") as HTMLInputElement;\n\n if (\n messageElem !== null &&\n userElem !== null &&\n statusElem !== null &&\n userElem !== null &&\n signInElem !== null &&\n passwordElem !== null\n ) {\n messageElem.innerText = getLocalizedString(message);\n\n userElem.value = af.userSession.login || \"\";\n userElem.disabled = !!af.userSession.login;\n userElem.readOnly = !!af.userSession.login;\n\n document.body.appendChild(contentContainer);\n\n const doLogin = async () => {\n passwordElem.disabled = true;\n\n const request = new Request(\"/login\", {\n body: JSON.stringify({\n username: userElem.value,\n password: passwordElem.value,\n remember: false\n }),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n },\n method: \"POST\"\n });\n\n try {\n const response = await fetch(request);\n const json = await response.json();\n\n if (json.success) {\n document.body.removeChild(contentContainer);\n this.showingDialog = false;\n this.eventHandler.emit(\"onAuthenticated\");\n\n if (statusElem.parentNode) {\n (statusElem.parentNode as HTMLElement).style.display = \"none\";\n }\n } else {\n throw new Error(json.error);\n }\n } catch (err) {\n if (err && typeof err === \"object\") {\n let error = err as Error;\n passwordElem.disabled = false;\n passwordElem.classList.toggle(\"invalid\", true);\n passwordElem.value = \"\";\n passwordElem.focus();\n statusElem.innerText = error.message ? error.message : String(error);\n\n if (statusElem.parentNode) {\n (statusElem.parentNode as HTMLElement).style.display = \"initial\";\n }\n }\n }\n };\n\n signInElem.addEventListener(\"click\", doLogin);\n\n passwordElem.addEventListener(\"keyup\", evt => {\n if (evt.key === \"Enter\") {\n doLogin();\n }\n });\n\n passwordElem.addEventListener(\"change\", evt => {\n if ((evt as KeyboardEvent).key === \"Enter\") {\n doLogin();\n }\n });\n\n userElem.addEventListener(\"keyup\", evt => {\n if (evt.key === \"Enter\") {\n doLogin();\n }\n });\n\n userElem.addEventListener(\"change\", evt => {\n if ((evt as KeyboardEvent).key === \"Enter\") {\n doLogin();\n }\n });\n\n passwordElem.focus();\n }\n }\n }\n\n attachEvent(eventName: SessionHandlerEvent, handler: Handler) {\n return this.eventHandler.on(eventName, handler);\n }\n\n detachEvent(eventName: SessionHandlerEvent, handler: Handler) {\n return this.eventHandler.off(eventName, handler);\n }\n}\n", "import SessionHandler from \"./SessionHandler.js\";\n\nexport default class UserSession extends SessionHandler {\n amDesignator: string = \"a.m.\";\n dayNames: string[] = [\"sunday\", \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\"];\n dayNamesShort: string[] = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n decimalSeparator: string = \".\";\n domain: string = \"OB\";\n email: string | null | undefined;\n formats: undefined | Record<string, string>;\n groupSeparator: string | null = null;\n integratedSecurity: boolean = false;\n isDeveloper: boolean = false;\n login: string = \"\";\n loginType: string | undefined;\n monthNames: string[] = [\"january\", \"february\", \"march\", \"april\", \"may\", \"june\", \"july\", \"august\", \"september\", \"october\", \"november\", \"december\", \"\"];\n monthNamesShort: string[] = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"augt\", \"sep\", \"oct\", \"nov\", \"dec\", \"\"];\n name: string | undefined;\n pmDesignator: string = \"p.m.\";\n shortDateFormat: string = \"dd.MM.yyyy\";\n culture: string = \"en-GB\";\n uiculture: string = \"en-GB\";\n expired: (callback: () => void) => void = () => null;\n\n constructor(userData: any) {\n super();\n this.formats = {};\n Object.assign(this, userData);\n }\n}\n", "export function downloadBlob(blob: Blob | MediaSource, fileName: string) {\n return new Promise<void>(function (resolve, reject) {\n try {\n const url = URL.createObjectURL(blob);\n const parent = document.body;\n const anchor = document.createElement(\"a\");\n anchor.setAttribute(\"download\", fileName);\n anchor.href = url;\n parent.append(anchor);\n anchor.click();\n parent.removeChild(anchor);\n\n setTimeout(function () {\n URL.revokeObjectURL(url);\n resolve();\n }, 250);\n } catch (ex) {\n reject(ex);\n }\n });\n}\n", "import { downloadBlob } from \"./downloadBlob.js\";\n\nexport type DownloadItem = {\n status: \"cancelled\" | \"error\" | \"requested\" | \"downloading\" | \"downloaded\" | \"completed\";\n bytesReceived?: number;\n error?: string;\n};\n\nexport type DownloadParameters = {\n signal?: AbortSignal;\n fileName: string;\n onProgress?: (progress: DownloadItem) => void;\n};\n\nexport async function downloadRequest(request: Request, { fileName, signal, onProgress }: DownloadParameters) {\n function reportProgress(progress: DownloadItem) {\n if (typeof onProgress === \"function\") {\n onProgress({ ...progress });\n }\n }\n\n let bytesReceived = 0;\n\n reportProgress({ status: \"requested\" });\n\n try {\n let response = await fetch(request);\n\n if (!response.ok || !response.body) {\n if (response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n let data = await response.json();\n if (data.error) {\n throw new Error(data.error);\n }\n }\n throw new Error(`${response.status} ${response.statusText}`);\n }\n\n try {\n const reader = response.body.getReader();\n const stream = new ReadableStream({\n start: function (controller) {\n function pump(): Promise<void> {\n return reader.read().then(function (read) {\n if (read.done) {\n controller.close();\n return;\n }\n\n bytesReceived += read.value.length;\n reportProgress({ bytesReceived, status: \"downloading\" });\n controller.enqueue(read.value);\n\n return pump();\n });\n }\n\n return pump();\n },\n });\n\n response = new Response(stream);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to replace response stream to log download progress.\");\n }\n\n const blob = await response.blob();\n\n reportProgress({ bytesReceived, status: \"downloaded\" });\n\n await downloadBlob(blob, fileName);\n\n reportProgress({ bytesReceived, status: \"completed\" });\n } catch (err) {\n if (signal?.aborted) {\n reportProgress({ status: \"cancelled\" });\n } else {\n reportProgress({ error: (err as Error).message, status: \"error\" });\n }\n }\n}\n", "const funcRegex = /^function(?:\\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\\s*\\(((?:(?:\\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\\s*,\\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\\s*\\)\\s*\\{((?:.|\\n|\\r)*)\\}$/;\n\nexport default function parseFunc(func: Function) {\n var match = func.toString().match(funcRegex);\n if (match === null) {\n throw new TypeError(\"Unable to parse function!\");\n }\n return { name: match[1], args: match[2].split(\",\"), body: match[3] };\n}\n", "function Namespace() {}\nNamespace.prototype = Object.create(null);\n\nexport default Namespace;\n", "import Namespace from \"./Namespace.js\";\n\nexport default function requireNamespace(\n root: any,\n namespace: string | Array<string>\n): any {\n if (typeof root === \"object\") {\n if (typeof namespace === \"string\") {\n let path = namespace.split(\".\");\n\n return requireNamespace(root, path);\n } else if (Array.isArray(namespace)) {\n let current: any = root;\n for (let i = 0; i < namespace.length; i++) {\n current = current[namespace[i]] =\n current[namespace[i]] || new (Namespace as any)();\n }\n\n return current;\n } else {\n throw new TypeError(\"Invalid type of parameter 'namespace'\");\n }\n } else {\n throw new TypeError(\"Invalid type of parameter 'root'\");\n }\n}\n", "/* eslint-disable no-console */\nexport default function warn(message: string, fallbackToAlert?: boolean) {\n console.warn(message);\n}\n", "import { has } from \"./has.js\";\nimport parseFunc from \"./parseFunc.js\";\nimport requireNamespace from \"./requireNamespace.js\";\nimport warn from \"./warn.js\";\n\n/**\n * Expose a value to a potentially deeply nested global variable\n * @param name {string | object} Either a dot-separated path to the global variable, or an object to expose the value on\n * @param value {object | Function | Function[]} The value(s) to expose\n */\nexport default function expose(name: object | string, value: object | Function | Function[]): void {\n if (arguments.length !== 2) {\n throw new Error(\"Incorrect number of arguments passed to the expose function!\");\n }\n\n if (Array.isArray(value)) {\n for (let func of value) {\n const { name: funcName } = parseFunc(func);\n\n if (funcName) {\n expose(name, func); // Expose func on namespace found in pName\n } else {\n throw new Error(\n \"Unable to detect name of function! Name it, or only supply one function and include name in first parameter.\"\n );\n }\n }\n } else {\n let keyName: string | undefined;\n let namespace;\n\n if (typeof value === \"function\") {\n keyName = parseFunc(value).name;\n }\n\n if (typeof name === \"string\") {\n let pathParts = name.split(\".\");\n\n if (!keyName) {\n keyName = pathParts[pathParts.length - 1];\n pathParts = pathParts.slice(0, pathParts.length - 1);\n }\n\n namespace = requireNamespace(window, pathParts);\n } else if (keyName && (typeof name === \"object\" || typeof name === \"function\")) {\n namespace = name;\n } else {\n throw new TypeError(\"Invalid typeof parameter 'name', or unable to parse pValue!\");\n }\n\n if (has(namespace, keyName)) {\n // If class is already defined, warn or show an alert\n warn([name, keyName].join(\".\") + \" is already defined!\");\n } else {\n namespace[keyName] = value;\n }\n }\n}\n", "function getLocalKey(key: string): string {\n return [af?.article?.id || \"\", \"common\", key].join(\".\");\n}\n\nclass LocalStorage {\n isPersisted() {\n return true;\n }\n\n getLocalStorageKey(key: string, global?: boolean) {\n return global ? [\"common\", key].join(\".\") : getLocalKey(key);\n }\n\n get(key: string, defaultValue: unknown, global?: boolean) {\n const lsKey = this.getLocalStorageKey(key, global);\n const value = localStorage.getItem(lsKey);\n\n return value !== null ? JSON.parse(value) : defaultValue;\n }\n\n set(key: string, value: unknown, global?: boolean) {\n localStorage.setItem(\n this.getLocalStorageKey(key, global),\n JSON.stringify(value)\n );\n }\n\n remove(key: string, global?: boolean) {\n const lsKey = this.getLocalStorageKey(key, global);\n if (localStorage.getItem(lsKey) !== null) {\n localStorage.removeItem(lsKey);\n return true;\n } else {\n return false;\n }\n }\n\n clear() {\n const baseKey = getLocalKey(\"\");\n\n for (let key in localStorage) {\n if (key.slice(0, baseKey.length) === baseKey) {\n localStorage.removeItem(key);\n }\n }\n }\n}\n\nexport default new LocalStorage();\n", "function getKey(article?: string) {\n const articleKey = article || af.article.id;\n return `${articleKey}.${af.userSession.login}`;\n}\n\nexport function getSettings<T>(setting: string, article?: string): T | null {\n if (!af?.userSession) return null;\n\n const key = getKey(article);\n const settings = JSON.parse(localStorage.getItem(key) || \"{}\");\n\n if (setting) {\n return settings[setting] || null;\n }\n\n return settings;\n}\n\nexport function saveSettings<T>(\n setting: string,\n value: T | null,\n article?: string\n): void {\n if (!af?.userSession) return;\n\n const key = getKey(article);\n let userSettings = JSON.parse(localStorage.getItem(key) || \"{}\");\n\n if (typeof value !== \"undefined\") {\n userSettings[setting] = value;\n } else {\n userSettings = setting;\n }\n\n localStorage.setItem(key, JSON.stringify(userSettings));\n}\n", "import \"./errorHandler.js\";\n\nimport UserSession from \"./UserSession.js\";\n\nexport { default as mitt } from \"mitt\";\nexport { downloadBlob } from \"./downloadBlob.js\";\nexport * from \"./downloadRequest.js\";\nexport { default as expose } from \"./expose.js\";\nexport { getLocalizedString } from \"./getLocalizedString.js\";\nexport * from \"./has.js\";\nexport { default as localStorage } from \"./localStorage.js\";\nexport { default as SessionHandler } from \"./SessionHandler.js\";\nexport { UserSession };\nexport * from \"./settings.js\";\n\nexport const version = __VERSION__;\n\ndeclare global {\n var __VERSION__: string;\n var __DEV__: number;\n var af: AfCore;\n\n interface Window {\n af: AfCore;\n }\n}\n\nexport interface AfArticle {\n hostName: string;\n i18n: Record<string, string>;\n id: string;\n}\n\nexport interface AfCore {\n article: AfArticle;\n common?: {\n getLocalizedString?: (string: string) => string;\n };\n controls?: {\n alert?: (message: string, callback?: () => void) => void;\n confirm?: (options: {\n title: string;\n message: string;\n buttons: string[];\n callback: (button: number) => void;\n }) => void;\n };\n userSession: UserSession;\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["event", "data", "all", "Map", "on", "type", "handler", "handlers", "get", "push", "set", "off", "splice", "indexOf", "emit", "evt", "slice", "map", "
|
|
3
|
+
"sources": ["../../src/errorHandler.ts", "../../../../node_modules/mitt/src/index.ts", "../../src/SessionHandler.ts", "../../src/UserSession.ts", "../../src/downloadBlob.ts", "../../src/downloadRequest.ts", "../../src/has.ts", "../../src/parseFunc.ts", "../../src/Namespace.ts", "../../src/requireNamespace.ts", "../../src/expose.ts", "../../src/getLocalizedString.ts", "../../src/localize.ts", "../../src/localStorage.ts", "../../src/settings.ts", "../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["window.addEventListener(\"error\", (event) => {\n try {\n // Try to avoid error-logging-loop\n const data = {\n error: event.error?.message ?? event.message ?? null,\n file: event.filename,\n line: event.lineno ?? 0,\n column: event.colno ?? 0,\n stack: event.error?.stack ?? null,\n };\n\n fetch(\"/data/Logger/LogError\", {\n body: JSON.stringify(data),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n method: \"POST\",\n });\n } catch (ex) {\n // ignore\n }\n});\n", "export type EventType = string | symbol;\n\n// An event handler can take an optional event argument\n// and should not return a value\nexport type Handler<T = unknown> = (event: T) => void;\nexport type WildcardHandler<T = Record<string, unknown>> = (\n\ttype: keyof T,\n\tevent: T[keyof T]\n) => void;\n\n// An array of all currently registered event handlers for a type\nexport type EventHandlerList<T = unknown> = Array<Handler<T>>;\nexport type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;\n\n// A map of event types and their corresponding event handlers.\nexport type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<\n\tkeyof Events | '*',\n\tEventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>\n>;\n\nexport interface Emitter<Events extends Record<EventType, unknown>> {\n\tall: EventHandlerMap<Events>;\n\n\ton<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;\n\ton(type: '*', handler: WildcardHandler<Events>): void;\n\n\toff<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;\n\toff(type: '*', handler: WildcardHandler<Events>): void;\n\n\temit<Key extends keyof Events>(type: Key, event: Events[Key]): void;\n\temit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;\n}\n\n/**\n * Mitt: Tiny (~200b) functional event emitter / pubsub.\n * @name mitt\n * @returns {Mitt}\n */\nexport default function mitt<Events extends Record<EventType, unknown>>(\n\tall?: EventHandlerMap<Events>\n): Emitter<Events> {\n\ttype GenericEventHandler =\n\t\t| Handler<Events[keyof Events]>\n\t\t| WildcardHandler<Events>;\n\tall = all || new Map();\n\n\treturn {\n\n\t\t/**\n\t\t * A Map of event names to registered handler functions.\n\t\t */\n\t\tall,\n\n\t\t/**\n\t\t * Register an event handler for the given type.\n\t\t * @param {string|symbol} type Type of event to listen for, or `'*'` for all events\n\t\t * @param {Function} handler Function to call in response to given event\n\t\t * @memberOf mitt\n\t\t */\n\t\ton<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {\n\t\t\tconst handlers: Array<GenericEventHandler> | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\thandlers.push(handler);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tall!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Remove an event handler for the given type.\n\t\t * If `handler` is omitted, all handlers of the given type are removed.\n\t\t * @param {string|symbol} type Type of event to unregister `handler` from, or `'*'`\n\t\t * @param {Function} [handler] Handler function to remove\n\t\t * @memberOf mitt\n\t\t */\n\t\toff<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {\n\t\t\tconst handlers: Array<GenericEventHandler> | undefined = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\tif (handler) {\n\t\t\t\t\thandlers.splice(handlers.indexOf(handler) >>> 0, 1);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tall!.set(type, []);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Invoke all handlers for the given type.\n\t\t * If present, `'*'` handlers are invoked after type-matched handlers.\n\t\t *\n\t\t * Note: Manually firing '*' handlers is not supported.\n\t\t *\n\t\t * @param {string|symbol} type The event type to invoke\n\t\t * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler\n\t\t * @memberOf mitt\n\t\t */\n\t\temit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {\n\t\t\tlet handlers = all!.get(type);\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as EventHandlerList<Events[keyof Events]>)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(evt!);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\thandlers = all!.get('*');\n\t\t\tif (handlers) {\n\t\t\t\t(handlers as WildCardEventHandlerList<Events>)\n\t\t\t\t\t.slice()\n\t\t\t\t\t.map((handler) => {\n\t\t\t\t\t\thandler(type, evt!);\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n", "import mitt, { Emitter, Handler } from \"mitt\";\n\ntype SessionHandlerEvent = \"onExpired\" | \"onAuthenticated\";\n\nexport default class SessionHandler {\n private eventHandler: Emitter<{ onAuthenticated: void; onExpired: void }> = mitt();\n\n authenticated() {\n this.eventHandler.emit(\"onAuthenticated\");\n }\n\n async expired(callback?: (() => void), type?: \"RequireTwoFactor\"): Promise<void> {\n let authPromise = new Promise<void>((resolve) => {\n let eventHandler = () => {\n this.eventHandler.off(\"onAuthenticated\", eventHandler);\n callback?.();\n resolve();\n }\n \n this.eventHandler.on(\"onAuthenticated\", eventHandler);\n });\n\n let dialog: HTMLDialogElement | null = document.querySelector(\"dialog.session-expired-dialog\");\n if (!dialog) {\n dialog = document.createElement(\"dialog\");\n dialog.className = \"session-expired-dialog\";\n dialog.style.display = \"flex\";\n dialog.style.padding = \"0\";\n dialog.style.left = \"50%\";\n dialog.style.transform = \"translateX(-50%)\";\n \n let link = \"/login?ReturnUrl=%2fapi/sessionexpired/remove\";\n if (type !== \"RequireTwoFactor\") {\n await fetch(\"/logout\", { method: \"POST\" });\n } else {\n link = \"/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove\";\n }\n\n dialog.innerHTML = `<iframe sandbox=\"allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms\" src=\"${link}\" style=\"border:0;width:min(500px,100vw);height:min(700px, 100vh);\"></iframe>`;\n document.body.append(dialog);\n dialog.showModal();\n await authPromise;\n dialog.remove();\n } else {\n await authPromise;\n }\n\n }\n\n attachEvent(eventName: SessionHandlerEvent, handler: Handler) {\n return this.eventHandler.on(eventName, handler);\n }\n\n detachEvent(eventName: SessionHandlerEvent, handler: Handler) {\n return this.eventHandler.off(eventName, handler);\n }\n}\n", "import SessionHandler from \"./SessionHandler.js\";\n\nexport class UserSession extends SessionHandler {\n amDesignator: string = \"a.m.\";\n dayNames: string[] = [\"sunday\", \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\"];\n dayNamesShort: string[] = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n decimalSeparator: string = \".\";\n domain: string = \"OB\";\n email: string | null | undefined;\n formats: undefined | Record<string, string>;\n groupSeparator: string | null = null;\n integratedSecurity: boolean = false;\n isDeveloper: boolean = false;\n login: string = \"\";\n loginType: string | undefined;\n monthNames: string[] = [\"january\", \"february\", \"march\", \"april\", \"may\", \"june\", \"july\", \"august\", \"september\", \"october\", \"november\", \"december\", \"\"];\n monthNamesShort: string[] = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"augt\", \"sep\", \"oct\", \"nov\", \"dec\", \"\"];\n name: string | undefined;\n pmDesignator: string = \"p.m.\";\n shortDateFormat: string = \"dd.MM.yyyy\";\n culture: string = \"en-GB\";\n uiculture: string = \"en-GB\";\n\n constructor(userData: any) {\n super();\n this.formats = {};\n Object.assign(this, userData);\n }\n}\n", "export function downloadBlob(blob: Blob | MediaSource, fileName: string) {\n return new Promise<void>(function (resolve, reject) {\n try {\n const url = URL.createObjectURL(blob);\n const parent = document.body;\n const anchor = document.createElement(\"a\");\n anchor.setAttribute(\"download\", fileName);\n anchor.href = url;\n parent.append(anchor);\n anchor.click();\n parent.removeChild(anchor);\n\n setTimeout(function () {\n URL.revokeObjectURL(url);\n resolve();\n }, 250);\n } catch (ex) {\n reject(ex);\n }\n });\n}\n", "import { downloadBlob } from \"./downloadBlob.js\";\n\nexport type DownloadItem = {\n status: \"cancelled\" | \"error\" | \"requested\" | \"downloading\" | \"downloaded\" | \"completed\";\n bytesReceived?: number;\n error?: string;\n};\n\nexport type DownloadParameters = {\n signal?: AbortSignal;\n fileName: string;\n onProgress?: (progress: DownloadItem) => void;\n};\n\nexport async function downloadRequest(request: Request, { fileName, signal, onProgress }: DownloadParameters) {\n function reportProgress(progress: DownloadItem) {\n if (typeof onProgress === \"function\") {\n onProgress({ ...progress });\n }\n }\n\n let bytesReceived = 0;\n\n reportProgress({ status: \"requested\" });\n\n try {\n let response = await fetch(request);\n\n if (!response.ok || !response.body) {\n if (response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n let data = await response.json();\n if (data.error) {\n throw new Error(data.error);\n }\n }\n throw new Error(`${response.status} ${response.statusText}`);\n }\n\n try {\n const reader = response.body.getReader();\n const stream = new ReadableStream({\n start: function (controller) {\n function pump(): Promise<void> {\n return reader.read().then(function (read) {\n if (read.done) {\n controller.close();\n return;\n }\n\n bytesReceived += read.value.length;\n reportProgress({ bytesReceived, status: \"downloading\" });\n controller.enqueue(read.value);\n\n return pump();\n });\n }\n\n return pump();\n },\n });\n\n response = new Response(stream);\n } catch (error) {}\n\n const blob = await response.blob();\n\n reportProgress({ bytesReceived, status: \"downloaded\" });\n\n await downloadBlob(blob, fileName);\n\n reportProgress({ bytesReceived, status: \"completed\" });\n } catch (err) {\n if (signal?.aborted) {\n reportProgress({ status: \"cancelled\" });\n } else {\n reportProgress({ error: (err as Error).message, status: \"error\" });\n }\n }\n}\n", "export function has(\n obj: any,\n key: string | number | symbol\n): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n", "const funcRegex = /^function(?:\\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\\s*\\(((?:(?:\\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\\s*,\\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\\s*\\)\\s*\\{((?:.|\\n|\\r)*)\\}$/;\n\nexport function parseFunc(func: Function) {\n var match = func.toString().match(funcRegex);\n if (match === null) {\n throw new TypeError(\"Unable to parse function!\");\n }\n return { name: match[1], args: match[2].split(\",\"), body: match[3] };\n}\n", "function Namespace() {}\nNamespace.prototype = Object.create(null);\n\nexport default Namespace;\n", "import Namespace from \"./Namespace.js\";\n\nexport function requireNamespace(\n root: any,\n namespace: string | Array<string>\n): any {\n if (typeof root === \"object\") {\n if (typeof namespace === \"string\") {\n let path = namespace.split(\".\");\n\n return requireNamespace(root, path);\n } else if (Array.isArray(namespace)) {\n let current: any = root;\n for (let i = 0; i < namespace.length; i++) {\n current = current[namespace[i]] =\n current[namespace[i]] || new (Namespace as any)();\n }\n\n return current;\n }\n }\n}\n", "import { has } from \"./has.js\";\nimport { parseFunc } from \"./parseFunc.js\";\nimport { requireNamespace } from \"./requireNamespace.js\";\n\n/**\n * Expose a value to a potentially deeply nested global variable\n * @param name {string | object} Either a dot-separated path to the global variable, or an object to expose the value on\n * @param value {object | Function | Function[]} The value(s) to expose\n */\nexport function expose(name: object | string, value: object | Function | Function[]): void {\n if (arguments.length !== 2) {\n throw new Error(\"Incorrect number of arguments passed to the expose function!\");\n }\n\n if (Array.isArray(value)) {\n for (let func of value) {\n const { name: funcName } = parseFunc(func);\n\n if (funcName) {\n expose(name, func); // Expose func on namespace found in pName\n } else {\n throw new Error(\n \"Unable to detect name of function! Name it, or only supply one function and include name in first parameter.\"\n );\n }\n }\n } else {\n let keyName: string | undefined;\n let namespace;\n\n if (typeof value === \"function\") {\n keyName = parseFunc(value).name;\n }\n\n if (typeof name === \"string\") {\n let pathParts = name.split(\".\");\n\n if (!keyName) {\n keyName = pathParts[pathParts.length - 1];\n pathParts = pathParts.slice(0, pathParts.length - 1);\n }\n\n namespace = requireNamespace(window, pathParts);\n } else if (keyName && (typeof name === \"object\" || typeof name === \"function\")) {\n namespace = name;\n } else {\n throw new TypeError(\"Invalid typeof parameter 'name', or unable to parse pValue!\");\n }\n\n if (has(namespace, keyName)) {\n // If class is already defined, warn or show an alert\n console.warn([name, keyName].join(\".\") + \" is already defined!\");\n } else {\n namespace[keyName] = value;\n }\n }\n}\n", "import { has } from \"./has\";\n\nasync function fetchLocalizedString(text: string) {\n try {\n let response = await fetch(`/api/user/localize/new/${af.article.id}`, {\n body: JSON.stringify({ text }),\n headers: {\n Accept: \"application/json; */*\",\n \"Content-Type\": \"application/json\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n method: \"POST\",\n });\n\n if (response.ok) {\n return (await response.json()) as string;\n }\n } catch (error) {}\n\n return text;\n}\nexport function getLocalizedStringAsync(string: undefined | null): undefined | null;\nexport function getLocalizedStringAsync(string: string): Promise<string>;\nexport function getLocalizedStringAsync(string: string | undefined | null) {\n if (!string) return string;\n\n return getLocalizedString(string, true);\n}\n\nexport function getLocalizedString(string: undefined | null): undefined | null;\nexport function getLocalizedString(string: string): string;\nexport function getLocalizedString(string: string, wait: false): string;\nexport function getLocalizedString(string: string, wait: true): Promise<string>;\nexport function getLocalizedString(string: undefined | null, wait: true): undefined | null;\nexport function getLocalizedString(\n string: string | undefined | null,\n wait?: boolean\n): string | undefined | null | Promise<string> {\n if (typeof string === \"string\" && string.trim().length === 0) {\n return string;\n }\n\n if (string === undefined || string === \"\" || string === null) {\n return;\n }\n\n if (af?.article?.i18n !== undefined) {\n if (!has(af.article.i18n, string)) {\n af.article.i18n[string] = string;\n\n let promise = fetchLocalizedString(string).then((text) => {\n af.article.i18n[string] = text;\n return text;\n });\n\n if (wait) {\n return promise;\n }\n }\n\n return af.article.i18n[string];\n } else {\n return string;\n }\n}\n", "import { getLocalizedString } from \"./getLocalizedString.js\";\n\n/**\n * Localization function for tagged templates. Replaces the arguments\n * with $n, where n is the index, before asking Appframe to translate\n * the string.\n * \n * For example, if you call localize`Page ${2} or ${5}`, the string\n * \"Page $0 of $1\" will be sent to Appframe, and for norwegian,\n * \"Side 2 av 5\" will be returned.\n * \n * @param stringParts \n * @param args \n * @returns Translated string\n */\nexport function localize(stringParts: TemplateStringsArray, ...args: any[]): string {\n if (!Array.isArray(stringParts) || stringParts?.length || stringParts.length !== args.length + 1) {\n throw TypeError(\"Method 'localize' must be used as a tag function\");\n }\n\n let stringToLocalize = stringParts.map((s, i) => (i === stringParts.length - 1 ? s : `${s}\\$${i}`)).join(\"\");\n let localized = getLocalizedString(stringToLocalize);\n\n args.forEach((arg, index) => {\n localized = localized.replace(\"$\" + index, arg);\n })\n\n return localized;\n}", "function getLocalKey(key: string): string {\n return [af?.article?.id || \"\", \"common\", key].join(\".\");\n}\n\nclass LocalStorage {\n isPersisted() {\n return true;\n }\n\n getLocalStorageKey(key: string, global?: boolean) {\n return global ? [\"common\", key].join(\".\") : getLocalKey(key);\n }\n\n get(key: string, defaultValue: unknown, global?: boolean) {\n const lsKey = this.getLocalStorageKey(key, global);\n const value = localStorage.getItem(lsKey);\n\n return value !== null ? JSON.parse(value) : defaultValue;\n }\n\n set(key: string, value: unknown, global?: boolean) {\n localStorage.setItem(\n this.getLocalStorageKey(key, global),\n JSON.stringify(value)\n );\n }\n\n remove(key: string, global?: boolean) {\n const lsKey = this.getLocalStorageKey(key, global);\n if (localStorage.getItem(lsKey) !== null) {\n localStorage.removeItem(lsKey);\n return true;\n } else {\n return false;\n }\n }\n\n clear() {\n const baseKey = getLocalKey(\"\");\n\n for (let key in localStorage) {\n if (key.slice(0, baseKey.length) === baseKey) {\n localStorage.removeItem(key);\n }\n }\n }\n}\n\nexport default new LocalStorage();\n", "function getKey(article?: string) {\n const articleKey = article || af.article.id;\n return `${articleKey}.${af.userSession.login}`;\n}\n\nexport function getSettings<T>(setting: string, article?: string): T | null {\n if (!af?.userSession) return null;\n\n const key = getKey(article);\n const settings = JSON.parse(localStorage.getItem(key) || \"{}\");\n\n if (setting) {\n return settings[setting] || null;\n }\n\n return settings;\n}\n\nexport function saveSettings<T>(\n setting: string,\n value: T | null,\n article?: string\n): void {\n if (!af?.userSession) return;\n\n const key = getKey(article);\n let userSettings = JSON.parse(localStorage.getItem(key) || \"{}\");\n\n if (typeof value !== \"undefined\") {\n userSettings[setting] = value;\n } else {\n userSettings = setting;\n }\n\n localStorage.setItem(key, JSON.stringify(userSettings));\n}\n", "import \"./errorHandler.js\";\n\nimport { UserSession } from \"./UserSession.js\";\n\nexport { default as mitt } from \"mitt\";\nexport { downloadBlob } from \"./downloadBlob.js\";\nexport * from \"./downloadRequest.js\";\nexport { expose } from \"./expose.js\";\nexport { getLocalizedString } from \"./getLocalizedString.js\";\nexport { localize } from \"./localize.js\";\nexport * from \"./has.js\";\nexport { default as localStorage } from \"./localStorage.js\";\nexport { default as SessionHandler } from \"./SessionHandler.js\";\nexport { UserSession };\nexport * from \"./settings.js\";\n\nexport const version = __VERSION__;\n\ndeclare global {\n var __VERSION__: string;\n var __DEV__: number;\n var af: AfCore;\n\n interface Window {\n af: AfCore;\n }\n}\n\nexport interface AfArticle {\n hostName: string;\n i18n: Record<string, string>;\n id: string;\n}\n\nexport interface AfCore {\n article: AfArticle;\n common?: {\n getLocalizedString?: (string: string) => string;\n };\n controls?: {\n alert?: (message: string, callback?: () => void) => void;\n confirm?: (options: {\n title: string;\n message: string;\n buttons: string[];\n callback: (button: number) => void;\n }) => void;\n };\n userSession: UserSession;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,iBAAiB,QAAUA,GAAU,CAC1C,GAAI,CAEF,IAAMC,EAAO,CACX,MAAOD,EAAM,OAAO,SAAWA,EAAM,SAAW,KAChD,KAAMA,EAAM,SACZ,KAAMA,EAAM,QAAU,EACtB,OAAQA,EAAM,OAAS,EACvB,MAAOA,EAAM,OAAO,OAAS,IAC/B,EAEA,MAAM,wBAAyB,CAC7B,KAAM,KAAK,UAAUC,CAAI,EACzB,QAAS,CACP,OAAQ,mBACR,eAAgB,kCAChB,mBAAoB,gBACtB,EACA,OAAQ,MACV,CAAC,CACH,MAAE,CAEF,CACF,CAAC,aCgBAC,EAAAA,CAOA,MAAO,CAKNA,IAPDA,EAAMA,GAAO,IAAIC,IAehBC,GAAAA,SAA6BC,EAAWC,EAAAA,CACvC,IAAMC,EAAmDL,EAAKM,IAAIH,CAAAA,EAC9DE,EACHA,EAASE,KAAKH,CAAAA,EAGdJ,EAAKQ,IAAIL,EAAM,CAACC,CAAAA,CAAAA,CAAAA,EAWlBK,IAAAA,SAA8BN,EAAWC,EAAAA,CACxC,IAAMC,EAAmDL,EAAKM,IAAIH,CAAAA,EAC9DE,IACCD,EACHC,EAASK,OAAOL,EAASM,QAAQP,CAAAA,IAAa,EAAG,CAAA,EAGjDJ,EAAKQ,IAAIL,EAAM,CAAA,CAAA,EAAA,EAelBS,KAAAA,SAA+BT,EAAWU,EAAAA,CACzC,IAAIR,EAAWL,EAAKM,IAAIH,CAAAA,EACpBE,GACFA,EACCS,MAAAA,EACAC,IA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AAO,KAE7B,IAAMG,EAAMJ,EAAOC,CAAO,EACpBI,EAAW,KAAK,MAAM,aAAa,QAAQD,CAAG,GAAK,IAAI,EAE7D,OAAID,EACKE,EAASF,IAAY,KAGvBE,CACT,CAEO,SAASC,GACdH,EACAI,EACAN,EACM,CACN,GAAI,CAAC,IAAI,YAAa,OAEtB,IAAMG,EAAMJ,EAAOC,CAAO,EACtBO,EAAe,KAAK,MAAM,aAAa,QAAQJ,CAAG,GAAK,IAAI,EAE3D,OAAOG,EAAU,IACnBC,EAAaL,GAAWI,EAExBC,EAAeL,EAGjB,aAAa,QAAQC,EAAK,KAAK,UAAUI,CAAY,CAAC,CACxD,CCnBO,IAAMC,GAAU",
|
|
6
|
+
"names": ["event", "data", "all", "Map", "on", "type", "handler", "handlers", "get", "push", "set", "off", "splice", "indexOf", "emit", "evt", "slice", "map", "SessionHandler", "mitt_default", "callback", "type", "authPromise", "resolve", "eventHandler", "dialog", "link", "eventName", "handler", "UserSession", "SessionHandler", "userData", "downloadBlob", "blob", "fileName", "resolve", "reject", "url", "parent", "anchor", "ex", "downloadRequest", "request", "fileName", "signal", "onProgress", "reportProgress", "progress", "bytesReceived", "response", "data", "reader", "stream", "controller", "pump", "read", "blob", "downloadBlob", "err", "has", "obj", "key", "funcRegex", "parseFunc", "func", "match", "Namespace", "Namespace_default", "requireNamespace", "root", "namespace", "path", "current", "i", "Namespace_default", "expose", "name", "value", "func", "funcName", "parseFunc", "keyName", "namespace", "pathParts", "requireNamespace", "has", "fetchLocalizedString", "text", "response", "getLocalizedString", "string", "wait", "has", "promise", "fetchLocalizedString", "text", "localize", "stringParts", "args", "stringToLocalize", "s", "i", "localized", "getLocalizedString", "arg", "index", "getLocalKey", "key", "LocalStorage", "global", "defaultValue", "lsKey", "value", "baseKey", "localStorage_default", "getKey", "article", "getSettings", "setting", "key", "settings", "saveSettings", "value", "userSettings", "version"]
|
|
7
7
|
}
|
package/dist/iife/af.common.js
CHANGED
|
@@ -4,7 +4,6 @@ var af;
|
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
7
|
var __export = (target, all) => {
|
|
9
8
|
for (var name in all)
|
|
10
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -18,10 +17,6 @@ var af;
|
|
|
18
17
|
return to;
|
|
19
18
|
};
|
|
20
19
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
-
var __publicField = (obj, key, value) => {
|
|
22
|
-
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
23
|
-
return value;
|
|
24
|
-
};
|
|
25
20
|
|
|
26
21
|
// src/index.ts
|
|
27
22
|
var src_exports = {};
|
|
@@ -35,6 +30,7 @@ var af;
|
|
|
35
30
|
getSettings: () => getSettings,
|
|
36
31
|
has: () => has,
|
|
37
32
|
localStorage: () => localStorage_default,
|
|
33
|
+
localize: () => localize,
|
|
38
34
|
mitt: () => mitt_default,
|
|
39
35
|
saveSettings: () => saveSettings,
|
|
40
36
|
version: () => version
|
|
@@ -81,181 +77,42 @@ var af;
|
|
|
81
77
|
} };
|
|
82
78
|
}
|
|
83
79
|
|
|
84
|
-
// src/has.ts
|
|
85
|
-
function has(obj, key) {
|
|
86
|
-
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// src/getLocalizedString.ts
|
|
90
|
-
async function fetchLocalizedString(text) {
|
|
91
|
-
try {
|
|
92
|
-
let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
|
|
93
|
-
body: JSON.stringify({ text }),
|
|
94
|
-
headers: {
|
|
95
|
-
Accept: "application/json; */*",
|
|
96
|
-
"Content-Type": "application/json",
|
|
97
|
-
"X-Requested-With": "XMLHttpRequest"
|
|
98
|
-
},
|
|
99
|
-
method: "POST"
|
|
100
|
-
});
|
|
101
|
-
if (response.ok) {
|
|
102
|
-
return await response.json();
|
|
103
|
-
}
|
|
104
|
-
} catch (error) {
|
|
105
|
-
}
|
|
106
|
-
return text;
|
|
107
|
-
}
|
|
108
|
-
function getLocalizedString(string, wait) {
|
|
109
|
-
if (typeof string === "string" && string.trim().length === 0) {
|
|
110
|
-
return string;
|
|
111
|
-
}
|
|
112
|
-
if (string === void 0 || string === "" || string === null) {
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
if (af?.article?.i18n !== void 0) {
|
|
116
|
-
if (!has(af.article.i18n, string)) {
|
|
117
|
-
af.article.i18n[string] = string;
|
|
118
|
-
let promise = fetchLocalizedString(string).then((text) => {
|
|
119
|
-
af.article.i18n[string] = text;
|
|
120
|
-
return text;
|
|
121
|
-
});
|
|
122
|
-
if (wait) {
|
|
123
|
-
return promise;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
return af.article.i18n[string];
|
|
127
|
-
} else {
|
|
128
|
-
return string;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
80
|
// src/SessionHandler.ts
|
|
133
|
-
var
|
|
81
|
+
var SessionHandler = class {
|
|
134
82
|
eventHandler = mitt_default();
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
this.
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
<input type="text" class="form-control" id="username" autofocus>
|
|
161
|
-
</div>
|
|
162
|
-
<div class="form-group">
|
|
163
|
-
<label for="password">${getLocalizedString("Password")}</label>
|
|
164
|
-
<input type="password" autocomplete="password" class="form-control" id="password" >
|
|
165
|
-
</div>
|
|
166
|
-
<div class="form-group">
|
|
167
|
-
<div>
|
|
168
|
-
<button type="submit" class="btn btn-default sign-in">
|
|
169
|
-
${getLocalizedString("Log in")}
|
|
170
|
-
</button>
|
|
171
|
-
</div>
|
|
172
|
-
</div>
|
|
173
|
-
</div>
|
|
174
|
-
</div>
|
|
175
|
-
<div class="row">
|
|
176
|
-
<div class="" style="display:none; margin: 0px 30px;">
|
|
177
|
-
<div class="alert alert-warning" role="alert" style="margin-top:10px;"></div>
|
|
178
|
-
</div>
|
|
179
|
-
</div>
|
|
180
|
-
</div>
|
|
181
|
-
`;
|
|
182
|
-
const message = af.userSession.login ? _SessionHandler.messages.relog : _SessionHandler.messages.login;
|
|
183
|
-
const messageElem = contentContainer.querySelector(".message");
|
|
184
|
-
const statusElem = contentContainer.querySelector(".alert-warning");
|
|
185
|
-
const userElem = contentContainer.querySelector("input[type=text]");
|
|
186
|
-
const signInElem = contentContainer.querySelector(".sign-in");
|
|
187
|
-
const passwordElem = contentContainer.querySelector("input[type=password]");
|
|
188
|
-
if (messageElem !== null && userElem !== null && statusElem !== null && userElem !== null && signInElem !== null && passwordElem !== null) {
|
|
189
|
-
messageElem.innerText = getLocalizedString(message);
|
|
190
|
-
userElem.value = af.userSession.login || "";
|
|
191
|
-
userElem.disabled = !!af.userSession.login;
|
|
192
|
-
userElem.readOnly = !!af.userSession.login;
|
|
193
|
-
document.body.appendChild(contentContainer);
|
|
194
|
-
const doLogin = async () => {
|
|
195
|
-
passwordElem.disabled = true;
|
|
196
|
-
const request = new Request("/login", {
|
|
197
|
-
body: JSON.stringify({
|
|
198
|
-
username: userElem.value,
|
|
199
|
-
password: passwordElem.value,
|
|
200
|
-
remember: false
|
|
201
|
-
}),
|
|
202
|
-
headers: {
|
|
203
|
-
Accept: "application/json",
|
|
204
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
205
|
-
"X-Requested-With": "XMLHttpRequest"
|
|
206
|
-
},
|
|
207
|
-
method: "POST"
|
|
208
|
-
});
|
|
209
|
-
try {
|
|
210
|
-
const response = await fetch(request);
|
|
211
|
-
const json = await response.json();
|
|
212
|
-
if (json.success) {
|
|
213
|
-
document.body.removeChild(contentContainer);
|
|
214
|
-
this.showingDialog = false;
|
|
215
|
-
this.eventHandler.emit("onAuthenticated");
|
|
216
|
-
if (statusElem.parentNode) {
|
|
217
|
-
statusElem.parentNode.style.display = "none";
|
|
218
|
-
}
|
|
219
|
-
} else {
|
|
220
|
-
throw new Error(json.error);
|
|
221
|
-
}
|
|
222
|
-
} catch (err) {
|
|
223
|
-
if (err && typeof err === "object") {
|
|
224
|
-
let error = err;
|
|
225
|
-
passwordElem.disabled = false;
|
|
226
|
-
passwordElem.classList.toggle("invalid", true);
|
|
227
|
-
passwordElem.value = "";
|
|
228
|
-
passwordElem.focus();
|
|
229
|
-
statusElem.innerText = error.message ? error.message : String(error);
|
|
230
|
-
if (statusElem.parentNode) {
|
|
231
|
-
statusElem.parentNode.style.display = "initial";
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
signInElem.addEventListener("click", doLogin);
|
|
237
|
-
passwordElem.addEventListener("keyup", (evt) => {
|
|
238
|
-
if (evt.key === "Enter") {
|
|
239
|
-
doLogin();
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
passwordElem.addEventListener("change", (evt) => {
|
|
243
|
-
if (evt.key === "Enter") {
|
|
244
|
-
doLogin();
|
|
245
|
-
}
|
|
246
|
-
});
|
|
247
|
-
userElem.addEventListener("keyup", (evt) => {
|
|
248
|
-
if (evt.key === "Enter") {
|
|
249
|
-
doLogin();
|
|
250
|
-
}
|
|
251
|
-
});
|
|
252
|
-
userElem.addEventListener("change", (evt) => {
|
|
253
|
-
if (evt.key === "Enter") {
|
|
254
|
-
doLogin();
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
passwordElem.focus();
|
|
83
|
+
authenticated() {
|
|
84
|
+
this.eventHandler.emit("onAuthenticated");
|
|
85
|
+
}
|
|
86
|
+
async expired(callback, type) {
|
|
87
|
+
let authPromise = new Promise((resolve) => {
|
|
88
|
+
let eventHandler = () => {
|
|
89
|
+
this.eventHandler.off("onAuthenticated", eventHandler);
|
|
90
|
+
callback?.();
|
|
91
|
+
resolve();
|
|
92
|
+
};
|
|
93
|
+
this.eventHandler.on("onAuthenticated", eventHandler);
|
|
94
|
+
});
|
|
95
|
+
let dialog = document.querySelector("dialog.session-expired-dialog");
|
|
96
|
+
if (!dialog) {
|
|
97
|
+
dialog = document.createElement("dialog");
|
|
98
|
+
dialog.className = "session-expired-dialog";
|
|
99
|
+
dialog.style.display = "flex";
|
|
100
|
+
dialog.style.padding = "0";
|
|
101
|
+
dialog.style.left = "50%";
|
|
102
|
+
dialog.style.transform = "translateX(-50%)";
|
|
103
|
+
let link = "/login?ReturnUrl=%2fapi/sessionexpired/remove";
|
|
104
|
+
if (type !== "RequireTwoFactor") {
|
|
105
|
+
await fetch("/logout", { method: "POST" });
|
|
106
|
+
} else {
|
|
107
|
+
link = "/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove";
|
|
258
108
|
}
|
|
109
|
+
dialog.innerHTML = `<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${link}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`;
|
|
110
|
+
document.body.append(dialog);
|
|
111
|
+
dialog.showModal();
|
|
112
|
+
await authPromise;
|
|
113
|
+
dialog.remove();
|
|
114
|
+
} else {
|
|
115
|
+
await authPromise;
|
|
259
116
|
}
|
|
260
117
|
}
|
|
261
118
|
attachEvent(eventName, handler) {
|
|
@@ -265,11 +122,6 @@ var af;
|
|
|
265
122
|
return this.eventHandler.off(eventName, handler);
|
|
266
123
|
}
|
|
267
124
|
};
|
|
268
|
-
var SessionHandler = _SessionHandler;
|
|
269
|
-
__publicField(SessionHandler, "messages", {
|
|
270
|
-
login: "Log in",
|
|
271
|
-
relog: "Session expired - log in"
|
|
272
|
-
});
|
|
273
125
|
|
|
274
126
|
// src/UserSession.ts
|
|
275
127
|
var UserSession = class extends SessionHandler {
|
|
@@ -292,7 +144,6 @@ var af;
|
|
|
292
144
|
shortDateFormat = "dd.MM.yyyy";
|
|
293
145
|
culture = "en-GB";
|
|
294
146
|
uiculture = "en-GB";
|
|
295
|
-
expired = () => null;
|
|
296
147
|
constructor(userData) {
|
|
297
148
|
super();
|
|
298
149
|
this.formats = {};
|
|
@@ -363,7 +214,6 @@ var af;
|
|
|
363
214
|
});
|
|
364
215
|
response = new Response(stream);
|
|
365
216
|
} catch (error) {
|
|
366
|
-
console.warn("Failed to replace response stream to log download progress.");
|
|
367
217
|
}
|
|
368
218
|
const blob = await response.blob();
|
|
369
219
|
reportProgress({ bytesReceived, status: "downloaded" });
|
|
@@ -378,6 +228,11 @@ var af;
|
|
|
378
228
|
}
|
|
379
229
|
}
|
|
380
230
|
|
|
231
|
+
// src/has.ts
|
|
232
|
+
function has(obj, key) {
|
|
233
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
234
|
+
}
|
|
235
|
+
|
|
381
236
|
// src/parseFunc.ts
|
|
382
237
|
var funcRegex = /^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;
|
|
383
238
|
function parseFunc(func) {
|
|
@@ -406,19 +261,10 @@ var af;
|
|
|
406
261
|
current = current[namespace[i]] = current[namespace[i]] || new Namespace_default();
|
|
407
262
|
}
|
|
408
263
|
return current;
|
|
409
|
-
} else {
|
|
410
|
-
throw new TypeError("Invalid type of parameter 'namespace'");
|
|
411
264
|
}
|
|
412
|
-
} else {
|
|
413
|
-
throw new TypeError("Invalid type of parameter 'root'");
|
|
414
265
|
}
|
|
415
266
|
}
|
|
416
267
|
|
|
417
|
-
// src/warn.ts
|
|
418
|
-
function warn(message, fallbackToAlert) {
|
|
419
|
-
console.warn(message);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
268
|
// src/expose.ts
|
|
423
269
|
function expose(name, value) {
|
|
424
270
|
if (arguments.length !== 2) {
|
|
@@ -454,13 +300,69 @@ var af;
|
|
|
454
300
|
throw new TypeError("Invalid typeof parameter 'name', or unable to parse pValue!");
|
|
455
301
|
}
|
|
456
302
|
if (has(namespace, keyName)) {
|
|
457
|
-
warn([name, keyName].join(".") + " is already defined!");
|
|
303
|
+
console.warn([name, keyName].join(".") + " is already defined!");
|
|
458
304
|
} else {
|
|
459
305
|
namespace[keyName] = value;
|
|
460
306
|
}
|
|
461
307
|
}
|
|
462
308
|
}
|
|
463
309
|
|
|
310
|
+
// src/getLocalizedString.ts
|
|
311
|
+
async function fetchLocalizedString(text) {
|
|
312
|
+
try {
|
|
313
|
+
let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
|
|
314
|
+
body: JSON.stringify({ text }),
|
|
315
|
+
headers: {
|
|
316
|
+
Accept: "application/json; */*",
|
|
317
|
+
"Content-Type": "application/json",
|
|
318
|
+
"X-Requested-With": "XMLHttpRequest"
|
|
319
|
+
},
|
|
320
|
+
method: "POST"
|
|
321
|
+
});
|
|
322
|
+
if (response.ok) {
|
|
323
|
+
return await response.json();
|
|
324
|
+
}
|
|
325
|
+
} catch (error) {
|
|
326
|
+
}
|
|
327
|
+
return text;
|
|
328
|
+
}
|
|
329
|
+
function getLocalizedString(string, wait) {
|
|
330
|
+
if (typeof string === "string" && string.trim().length === 0) {
|
|
331
|
+
return string;
|
|
332
|
+
}
|
|
333
|
+
if (string === void 0 || string === "" || string === null) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (af?.article?.i18n !== void 0) {
|
|
337
|
+
if (!has(af.article.i18n, string)) {
|
|
338
|
+
af.article.i18n[string] = string;
|
|
339
|
+
let promise = fetchLocalizedString(string).then((text) => {
|
|
340
|
+
af.article.i18n[string] = text;
|
|
341
|
+
return text;
|
|
342
|
+
});
|
|
343
|
+
if (wait) {
|
|
344
|
+
return promise;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return af.article.i18n[string];
|
|
348
|
+
} else {
|
|
349
|
+
return string;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/localize.ts
|
|
354
|
+
function localize(stringParts, ...args) {
|
|
355
|
+
if (!Array.isArray(stringParts) || stringParts?.length || stringParts.length !== args.length + 1) {
|
|
356
|
+
throw TypeError("Method 'localize' must be used as a tag function");
|
|
357
|
+
}
|
|
358
|
+
let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
|
|
359
|
+
let localized = getLocalizedString(stringToLocalize);
|
|
360
|
+
args.forEach((arg, index) => {
|
|
361
|
+
localized = localized.replace("$" + index, arg);
|
|
362
|
+
});
|
|
363
|
+
return localized;
|
|
364
|
+
}
|
|
365
|
+
|
|
464
366
|
// src/localStorage.ts
|
|
465
367
|
function getLocalKey(key) {
|
|
466
368
|
return [af?.article?.id || "", "common", key].join(".");
|
|
@@ -532,6 +434,6 @@ var af;
|
|
|
532
434
|
}
|
|
533
435
|
|
|
534
436
|
// src/index.ts
|
|
535
|
-
var version = "2.0
|
|
437
|
+
var version = "2.1.0";
|
|
536
438
|
return __toCommonJS(src_exports);
|
|
537
439
|
})();
|