@kwiz/common 1.0.96 → 1.0.97

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.
Files changed (100) hide show
  1. package/.github/workflows/npm-publish.yml +24 -24
  2. package/.madgerc +2 -2
  3. package/LICENSE +21 -21
  4. package/fix-folder-imports.js +26 -26
  5. package/lib/cjs/helpers/strings.js +20 -1
  6. package/lib/cjs/helpers/strings.js.map +1 -1
  7. package/lib/cjs/types/libs/msal.types.js +26 -26
  8. package/lib/cjs/utils/sharepoint.rest/user.js +11 -11
  9. package/lib/esm/helpers/strings.js +19 -1
  10. package/lib/esm/helpers/strings.js.map +1 -1
  11. package/lib/esm/types/libs/msal.types.js +26 -26
  12. package/lib/esm/utils/sharepoint.rest/user.js +11 -11
  13. package/lib/types/helpers/strings.d.ts +5 -0
  14. package/package.json +81 -81
  15. package/readme.md +17 -17
  16. package/src/_dependencies.ts +12 -12
  17. package/src/config.ts +17 -17
  18. package/src/helpers/Guid.ts +181 -181
  19. package/src/helpers/base64.ts +173 -173
  20. package/src/helpers/browser.test.js +13 -13
  21. package/src/helpers/browser.ts +1399 -1399
  22. package/src/helpers/browserinfo.ts +292 -292
  23. package/src/helpers/collections.base.test.js +25 -25
  24. package/src/helpers/collections.base.ts +437 -437
  25. package/src/helpers/collections.ts +107 -107
  26. package/src/helpers/color.ts +54 -54
  27. package/src/helpers/cookies.ts +59 -59
  28. package/src/helpers/date.test.js +119 -119
  29. package/src/helpers/date.ts +188 -188
  30. package/src/helpers/debug.ts +186 -186
  31. package/src/helpers/diagrams.ts +43 -43
  32. package/src/helpers/emails.ts +6 -6
  33. package/src/helpers/eval.ts +5 -5
  34. package/src/helpers/file.test.js +50 -50
  35. package/src/helpers/file.ts +60 -60
  36. package/src/helpers/flatted.ts +149 -149
  37. package/src/helpers/functions.ts +16 -16
  38. package/src/helpers/graph/calendar.types.ts +10 -10
  39. package/src/helpers/http.ts +69 -69
  40. package/src/helpers/images.ts +22 -22
  41. package/src/helpers/json.ts +38 -38
  42. package/src/helpers/md5.ts +189 -189
  43. package/src/helpers/objects.test.js +33 -33
  44. package/src/helpers/objects.ts +274 -274
  45. package/src/helpers/promises.test.js +37 -37
  46. package/src/helpers/promises.ts +165 -165
  47. package/src/helpers/random.ts +27 -27
  48. package/src/helpers/scheduler/scheduler.test.js +103 -103
  49. package/src/helpers/scheduler/scheduler.ts +131 -131
  50. package/src/helpers/sharepoint.ts +776 -776
  51. package/src/helpers/strings.test.js +122 -101
  52. package/src/helpers/strings.ts +337 -317
  53. package/src/helpers/typecheckers.test.js +34 -34
  54. package/src/helpers/typecheckers.ts +266 -266
  55. package/src/helpers/url.test.js +43 -43
  56. package/src/helpers/url.ts +207 -207
  57. package/src/helpers/urlhelper.ts +111 -111
  58. package/src/index.ts +6 -6
  59. package/src/types/auth.ts +54 -54
  60. package/src/types/common.types.ts +15 -15
  61. package/src/types/flatted.types.ts +59 -59
  62. package/src/types/globals.types.ts +6 -6
  63. package/src/types/graph/calendar.types.ts +80 -80
  64. package/src/types/knownscript.types.ts +18 -18
  65. package/src/types/libs/datajs.types.ts +28 -28
  66. package/src/types/libs/ics.types.ts +30 -30
  67. package/src/types/libs/msal.types.ts +49 -49
  68. package/src/types/locales.ts +124 -124
  69. package/src/types/localstoragecache.types.ts +8 -8
  70. package/src/types/location.types.ts +27 -27
  71. package/src/types/moment.ts +11 -11
  72. package/src/types/regex.types.ts +16 -16
  73. package/src/types/rest.types.ts +95 -95
  74. package/src/types/sharepoint.types.ts +1465 -1465
  75. package/src/types/sharepoint.utils.types.ts +287 -287
  76. package/src/utils/auth/common.ts +74 -74
  77. package/src/utils/auth/discovery.test.js +12 -12
  78. package/src/utils/auth/discovery.ts +132 -132
  79. package/src/utils/base64.ts +27 -27
  80. package/src/utils/consolelogger.ts +320 -320
  81. package/src/utils/date.ts +35 -35
  82. package/src/utils/emails.ts +24 -24
  83. package/src/utils/knownscript.ts +286 -286
  84. package/src/utils/localstoragecache.ts +441 -441
  85. package/src/utils/rest.ts +501 -501
  86. package/src/utils/script.ts +170 -170
  87. package/src/utils/sharepoint.rest/common.ts +154 -154
  88. package/src/utils/sharepoint.rest/date.ts +62 -62
  89. package/src/utils/sharepoint.rest/file.folder.ts +598 -598
  90. package/src/utils/sharepoint.rest/item.ts +547 -547
  91. package/src/utils/sharepoint.rest/list.ts +1480 -1480
  92. package/src/utils/sharepoint.rest/listutils/GetListItemsByCaml.ts +774 -774
  93. package/src/utils/sharepoint.rest/listutils/GetListItemsById.ts +275 -275
  94. package/src/utils/sharepoint.rest/listutils/common.ts +206 -206
  95. package/src/utils/sharepoint.rest/location.ts +141 -141
  96. package/src/utils/sharepoint.rest/navigation-links.ts +86 -86
  97. package/src/utils/sharepoint.rest/user-search.ts +252 -252
  98. package/src/utils/sharepoint.rest/user.ts +491 -491
  99. package/src/utils/sharepoint.rest/web.ts +1384 -1384
  100. package/src/utils/sod.ts +194 -194
@@ -1,171 +1,171 @@
1
- import { isDebug } from "../helpers/debug";
2
- import { noop } from "../helpers/objects";
3
- import { isNotEmptyArray, isNullOrEmptyString, isNullOrUndefined } from "../helpers/typecheckers";
4
- import { IKnownScript, ksGlobal } from "../types/knownscript.types";
5
- import Sod from "./sod";
6
-
7
- export interface IScriptUtils {
8
- /** @deprecated - use wrapFunction instead from helpers/functions */
9
- wrapFunction3?: (originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) => void;
10
- loadKnownScript: (script: IKnownScript) => void;
11
- loadKnownScript_Sync: (script: IKnownScript) => void;
12
- ensureScript: (scriptUrl: string, global: ksGlobal, callback: () => void, sodName: string) => void;
13
- ensureScripts: (scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) => void;
14
- }
15
-
16
- export default class script implements IScriptUtils {
17
- private static instance: script = null;
18
- public isRtl = false;
19
- public static get Instance() {
20
- if (script.instance === null) {
21
- //share single instance between all imports
22
- if (typeof (window as any).kSingleScripts !== 'undefined')
23
- script.instance = (window as any).kSingleScripts;//a global instance already exists, use it
24
- else {
25
- script.instance = new script();
26
- (window as any).kSingleScripts = script.instance;//place this instance in the global namespace for others to reuse
27
- }
28
- }
29
- return script.instance;
30
- }
31
-
32
- public async loadKnownScript(knownScript: IKnownScript) {
33
- var promisesDependencies: Promise<any>[] = [];
34
- (knownScript.dependencies || []).forEach(dep => {
35
- promisesDependencies.push(this.loadKnownScript(dep));
36
- });
37
-
38
- if (promisesDependencies.length > 0)
39
- await Promise.all(promisesDependencies);
40
-
41
- return new Promise((resolve, reject) => {
42
- this.ensureKnownScriptInternal(knownScript, () => {
43
- resolve(Sod.getGlobal(knownScript.global));
44
- });
45
- });
46
- }
47
- public loadKnownScript_Sync(knownScript: IKnownScript) {
48
- try {
49
- if (isNotEmptyArray(knownScript.dependencies)) {
50
- (knownScript.dependencies || []).forEach(dep => {
51
- this.loadKnownScript_Sync(dep)
52
- });
53
- }
54
- } catch {
55
- }
56
-
57
- this.ensureKnownScriptInternal(knownScript, noop, true);
58
- return Sod.getGlobal(knownScript.global);
59
- }
60
-
61
- private ensureKnownScriptInternal(knownScript: IKnownScript, callback: () => void, sync = false) {
62
- let url = isDebug() && !knownScript.forceMin ? knownScript.url.replace('.min.js', '.js') : knownScript.url;
63
- if (url[0] === '/') url = "https://apps.kwizcom.com" + url;
64
-
65
- if (sync === true)
66
- this.ensureScriptSync(url, knownScript.global, callback, knownScript.sodName);
67
- else
68
- this.ensureScript(url, knownScript.global, callback, knownScript.sodName);
69
-
70
- let cssFiles = this.isRtl === true && !isNullOrUndefined(knownScript.rtlCss) ? knownScript.rtlCss : knownScript.css;
71
- if (!isNullOrUndefined(cssFiles))
72
- cssFiles.forEach(css => {
73
- if (!isNullOrEmptyString(css)) {
74
- let cssurl = isDebug() && !knownScript.forceMin ? css.replace('.min.css', '.css') : css;
75
- if (cssurl[0] === '/') cssurl = "https://apps.kwizcom.com" + cssurl;
76
-
77
- let knownStyles = document.getElementsByClassName("kwizcom_known_css");
78
- let found = false;
79
- for (let si = 0; si < knownStyles.length; si++) {
80
- let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
81
- if (elm.href && elm.href.toLowerCase() === cssurl.toLowerCase()) {
82
- found = true;
83
- break;
84
- }
85
- }
86
- if (!found) {
87
- let link = document.createElement("link");
88
- link.rel = "stylesheet";
89
- link.className = "kwizcom_known_css";
90
- link.type = "text/css";
91
- link.href = cssurl;
92
- document.head.appendChild(link);
93
- }
94
- }
95
- });
96
- }
97
-
98
- public loadCss(cssUrl: string) {
99
- let knownStyles = document.getElementsByClassName("kwizcom_known_css");
100
- let found = false;
101
- for (let si = 0; si < knownStyles.length; si++) {
102
- let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
103
- if (elm.href && elm.href.toLowerCase() === cssUrl.toLowerCase()) {
104
- found = true;
105
- break;
106
- }
107
- }
108
- if (!found) {
109
- let link = document.createElement("link");
110
- link.rel = "stylesheet";
111
- link.className = "kwizcom_known_css";
112
- link.type = "text/css";
113
- link.href = cssUrl;
114
- document.head.appendChild(link);
115
- }
116
- }
117
-
118
- public ensureScriptSync(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
119
- //in IE there is no promise, we cannot use any async functions
120
- return Sod.ensureScriptNoPromise(scriptUrl, global, callback, sodName, true);
121
- }
122
- public async ensureScript(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
123
- return Sod.ensureScript(scriptUrl, global, callback, sodName, false);
124
- }
125
- /** ensure a collection of scripts and call the callback when they are all done */
126
- public async ensureScripts(scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) {
127
- let promises: Promise<void>[] = [];
128
- let length = scripts.length;
129
- let finished = 0;
130
- let onFinished = typeof (callback) !== "function" ? null : () => {
131
- finished++;
132
- if (finished === length)//all finished
133
- callback();
134
- };
135
- scripts.forEach(scr => {
136
- promises.push(Sod.ensureScript(scr.scriptUrl, scr.global, onFinished, scr.sodName));
137
- });
138
-
139
- return Promise.all(promises);
140
- }
141
-
142
- private _WrapFunctionArr: any[] = [];
143
-
144
- /** @deprecated - use wrapFunction instead from helpers/functions */
145
- public wrapFunction3(originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) {
146
- try {
147
- if (instance !== null) {
148
- originalFunction.bind(instance);
149
- }
150
- var idx = this._WrapFunctionArr.length;
151
- this._WrapFunctionArr[idx] = originalFunction;
152
-
153
- originalFunction = function (...args: any[]) {
154
- if (typeof (doBefore) === "function") {
155
- doBefore.apply(instance, args);
156
- }
157
- var returnValue = this._WrapFunctionArr[idx].apply(instance, args);
158
- if (typeof (doAfter) === "function") {
159
- doAfter.apply(instance, args);
160
- }
161
-
162
- return returnValue;
163
- };
164
- if (instance !== null) {
165
- originalFunction.bind(instance);
166
- }
167
- } catch (e) {
168
- if (isDebug()) console.log('unhandled error in wrapFunction3');
169
- }
170
- }
1
+ import { isDebug } from "../helpers/debug";
2
+ import { noop } from "../helpers/objects";
3
+ import { isNotEmptyArray, isNullOrEmptyString, isNullOrUndefined } from "../helpers/typecheckers";
4
+ import { IKnownScript, ksGlobal } from "../types/knownscript.types";
5
+ import Sod from "./sod";
6
+
7
+ export interface IScriptUtils {
8
+ /** @deprecated - use wrapFunction instead from helpers/functions */
9
+ wrapFunction3?: (originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) => void;
10
+ loadKnownScript: (script: IKnownScript) => void;
11
+ loadKnownScript_Sync: (script: IKnownScript) => void;
12
+ ensureScript: (scriptUrl: string, global: ksGlobal, callback: () => void, sodName: string) => void;
13
+ ensureScripts: (scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) => void;
14
+ }
15
+
16
+ export default class script implements IScriptUtils {
17
+ private static instance: script = null;
18
+ public isRtl = false;
19
+ public static get Instance() {
20
+ if (script.instance === null) {
21
+ //share single instance between all imports
22
+ if (typeof (window as any).kSingleScripts !== 'undefined')
23
+ script.instance = (window as any).kSingleScripts;//a global instance already exists, use it
24
+ else {
25
+ script.instance = new script();
26
+ (window as any).kSingleScripts = script.instance;//place this instance in the global namespace for others to reuse
27
+ }
28
+ }
29
+ return script.instance;
30
+ }
31
+
32
+ public async loadKnownScript(knownScript: IKnownScript) {
33
+ var promisesDependencies: Promise<any>[] = [];
34
+ (knownScript.dependencies || []).forEach(dep => {
35
+ promisesDependencies.push(this.loadKnownScript(dep));
36
+ });
37
+
38
+ if (promisesDependencies.length > 0)
39
+ await Promise.all(promisesDependencies);
40
+
41
+ return new Promise((resolve, reject) => {
42
+ this.ensureKnownScriptInternal(knownScript, () => {
43
+ resolve(Sod.getGlobal(knownScript.global));
44
+ });
45
+ });
46
+ }
47
+ public loadKnownScript_Sync(knownScript: IKnownScript) {
48
+ try {
49
+ if (isNotEmptyArray(knownScript.dependencies)) {
50
+ (knownScript.dependencies || []).forEach(dep => {
51
+ this.loadKnownScript_Sync(dep)
52
+ });
53
+ }
54
+ } catch {
55
+ }
56
+
57
+ this.ensureKnownScriptInternal(knownScript, noop, true);
58
+ return Sod.getGlobal(knownScript.global);
59
+ }
60
+
61
+ private ensureKnownScriptInternal(knownScript: IKnownScript, callback: () => void, sync = false) {
62
+ let url = isDebug() && !knownScript.forceMin ? knownScript.url.replace('.min.js', '.js') : knownScript.url;
63
+ if (url[0] === '/') url = "https://apps.kwizcom.com" + url;
64
+
65
+ if (sync === true)
66
+ this.ensureScriptSync(url, knownScript.global, callback, knownScript.sodName);
67
+ else
68
+ this.ensureScript(url, knownScript.global, callback, knownScript.sodName);
69
+
70
+ let cssFiles = this.isRtl === true && !isNullOrUndefined(knownScript.rtlCss) ? knownScript.rtlCss : knownScript.css;
71
+ if (!isNullOrUndefined(cssFiles))
72
+ cssFiles.forEach(css => {
73
+ if (!isNullOrEmptyString(css)) {
74
+ let cssurl = isDebug() && !knownScript.forceMin ? css.replace('.min.css', '.css') : css;
75
+ if (cssurl[0] === '/') cssurl = "https://apps.kwizcom.com" + cssurl;
76
+
77
+ let knownStyles = document.getElementsByClassName("kwizcom_known_css");
78
+ let found = false;
79
+ for (let si = 0; si < knownStyles.length; si++) {
80
+ let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
81
+ if (elm.href && elm.href.toLowerCase() === cssurl.toLowerCase()) {
82
+ found = true;
83
+ break;
84
+ }
85
+ }
86
+ if (!found) {
87
+ let link = document.createElement("link");
88
+ link.rel = "stylesheet";
89
+ link.className = "kwizcom_known_css";
90
+ link.type = "text/css";
91
+ link.href = cssurl;
92
+ document.head.appendChild(link);
93
+ }
94
+ }
95
+ });
96
+ }
97
+
98
+ public loadCss(cssUrl: string) {
99
+ let knownStyles = document.getElementsByClassName("kwizcom_known_css");
100
+ let found = false;
101
+ for (let si = 0; si < knownStyles.length; si++) {
102
+ let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
103
+ if (elm.href && elm.href.toLowerCase() === cssUrl.toLowerCase()) {
104
+ found = true;
105
+ break;
106
+ }
107
+ }
108
+ if (!found) {
109
+ let link = document.createElement("link");
110
+ link.rel = "stylesheet";
111
+ link.className = "kwizcom_known_css";
112
+ link.type = "text/css";
113
+ link.href = cssUrl;
114
+ document.head.appendChild(link);
115
+ }
116
+ }
117
+
118
+ public ensureScriptSync(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
119
+ //in IE there is no promise, we cannot use any async functions
120
+ return Sod.ensureScriptNoPromise(scriptUrl, global, callback, sodName, true);
121
+ }
122
+ public async ensureScript(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
123
+ return Sod.ensureScript(scriptUrl, global, callback, sodName, false);
124
+ }
125
+ /** ensure a collection of scripts and call the callback when they are all done */
126
+ public async ensureScripts(scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) {
127
+ let promises: Promise<void>[] = [];
128
+ let length = scripts.length;
129
+ let finished = 0;
130
+ let onFinished = typeof (callback) !== "function" ? null : () => {
131
+ finished++;
132
+ if (finished === length)//all finished
133
+ callback();
134
+ };
135
+ scripts.forEach(scr => {
136
+ promises.push(Sod.ensureScript(scr.scriptUrl, scr.global, onFinished, scr.sodName));
137
+ });
138
+
139
+ return Promise.all(promises);
140
+ }
141
+
142
+ private _WrapFunctionArr: any[] = [];
143
+
144
+ /** @deprecated - use wrapFunction instead from helpers/functions */
145
+ public wrapFunction3(originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) {
146
+ try {
147
+ if (instance !== null) {
148
+ originalFunction.bind(instance);
149
+ }
150
+ var idx = this._WrapFunctionArr.length;
151
+ this._WrapFunctionArr[idx] = originalFunction;
152
+
153
+ originalFunction = function (...args: any[]) {
154
+ if (typeof (doBefore) === "function") {
155
+ doBefore.apply(instance, args);
156
+ }
157
+ var returnValue = this._WrapFunctionArr[idx].apply(instance, args);
158
+ if (typeof (doAfter) === "function") {
159
+ doAfter.apply(instance, args);
160
+ }
161
+
162
+ return returnValue;
163
+ };
164
+ if (instance !== null) {
165
+ originalFunction.bind(instance);
166
+ }
167
+ } catch (e) {
168
+ if (isDebug()) console.log('unhandled error in wrapFunction3');
169
+ }
170
+ }
171
171
  }
@@ -1,155 +1,155 @@
1
- import { jsonParse } from "../../helpers/json";
2
- import { isNullOrEmptyString, isNullOrUndefined, isString, isValidGuid } from "../../helpers/typecheckers";
3
- import { makeServerRelativeUrl, normalizeUrl } from "../../helpers/url";
4
- import { IDictionary } from "../../types/common.types";
5
- import { IRestError } from "../../types/rest.types";
6
- import { FieldTypeAsString, IFieldInfoEX, IFieldTaxonomyInfo } from "../../types/sharepoint.types";
7
- import { ISPRestError } from "../../types/sharepoint.utils.types";
8
- import { ConsoleLogger } from "../consolelogger";
9
- import { getCacheItem, setCacheItem } from "../localstoragecache";
10
- import { mediumLocalCache } from "../rest";
11
- import { GetWebIdSync, GetWebInfoSync } from "./web";
12
-
13
- const logger = ConsoleLogger.get("sharepoint.rest/common");
14
-
15
- export const LIST_SELECT = `ListExperienceOptions,EffectiveBasePermissions,Description,Title,EnableAttachments,EnableModeration,BaseTemplate,BaseType,Id,Hidden,IsApplicationList,IsPrivate,IsCatalog,ImageUrl,ItemCount,ParentWebUrl,EntityTypeName,DefaultViewUrl,ParentWeb/Id,ParentWeb/Title`;
16
- export const LIST_EXPAND = `ParentWeb/Id,ParentWeb/Title`;
17
- export const WEB_SELECT = "Title,ServerRelativeUrl,Id,WebTemplate,Description,SiteLogoUrl";
18
- export const CONTENT_TYPES_SELECT = "Name,Description,StringId,Group,Hidden,ReadOnly,NewFormUrl,DisplayFormUrl,EditFormUrl,Sealed,MobileDisplayFormUrl,MobileNewFormUrl,MobileEditFormUrl,NewFormTemplateName,DisplayFormTemplateName,EditFormTemplateName";
19
- export const CONTENT_TYPES_SELECT_WITH_FIELDS = `${CONTENT_TYPES_SELECT},Fields`;
20
-
21
- export function hasGlobalContext() {
22
- //_spPageContextInfo.webServerRelativeUrl can be empty string
23
- return typeof (_spPageContextInfo) !== "undefined" && isString(_spPageContextInfo.webServerRelativeUrl);
24
- }
25
-
26
- export function GetFileSiteUrl(fileUrl: string): string {
27
- let siteUrl: string;
28
- let urlParts = fileUrl.split('/');
29
- if (urlParts[urlParts.length - 1].indexOf('.') > 0)//file name
30
- urlParts.pop();//file name
31
-
32
- let key = "GetSiteUrl|" + urlParts.join("/").toLowerCase();
33
- siteUrl = getCacheItem<string>(key);
34
- if (isNullOrUndefined(siteUrl)) {
35
- while (!isValidGuid(GetWebIdSync(urlParts.join('/'))))
36
- urlParts.pop();
37
-
38
- siteUrl = normalizeUrl(urlParts.join('/'));
39
- setCacheItem(key, siteUrl, mediumLocalCache.localStorageExpiration);//keep for 15 minutes
40
- }
41
- //must end with / otherwise root sites will return "" and we will think there is no site url.
42
- return makeServerRelativeUrl(normalizeUrl(siteUrl, true));
43
- }
44
-
45
- /** gets a site URL or null, returns the current web URL or siteUrl as relative URL - end with /
46
- * If you send a guid - it will look for a site with that ID in the current context site collection
47
- */
48
- export function GetSiteUrl(siteUrlOrId?: string): string {
49
- let siteUrl: string;
50
- if (isNullOrUndefined(siteUrlOrId)) {
51
- if (hasGlobalContext()) {
52
- siteUrl = _spPageContextInfo.webServerRelativeUrl;
53
- if (_spPageContextInfo.isAppWeb)//#1300 if in a classic app sub-site
54
- siteUrl = siteUrl.substring(0, siteUrl.lastIndexOf("/"));
55
- }
56
- else {
57
- siteUrl = GetFileSiteUrl(window.location.pathname);
58
- }
59
- }
60
- else if (isValidGuid(siteUrlOrId)) {
61
- //GetWebInfoSync calls GetSiteUrl recursively, but with null should not get in here
62
- let webInfo = GetWebInfoSync(null, siteUrlOrId);
63
- siteUrl = webInfo.ServerRelativeUrl;
64
- }
65
- else siteUrl = siteUrlOrId;
66
-
67
- //must end with / otherwise root sites will return "" and we will think there is no site url.
68
- return makeServerRelativeUrl(normalizeUrl(siteUrl, true));
69
- }
70
-
71
- /** gets a site url, returns its REST _api url */
72
- export function GetRestBaseUrl(siteUrl: string): string {
73
- siteUrl = GetSiteUrl(siteUrl);
74
- return siteUrl + '_api';
75
- }
76
-
77
- /** Get the field internal name as you can find it in item.FieldValuesAsText[name] (Or FieldValuesForEdit) */
78
- export function DecodeFieldValuesAsTextKey(key: string): string {
79
- return key.replace(/_x005f_/g, "_").replace('OData__', '_');
80
- }
81
-
82
- /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */
83
- export function DecodeFieldValuesAsText(FieldValuesAsText: IDictionary<string>) {
84
- return DecodeFieldValuesForEdit(FieldValuesAsText);
85
- }
86
- /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */
87
- export function DecodeFieldValuesForEdit(FieldValuesForEdit: IDictionary<string>) {
88
- let result: IDictionary<string> = {};
89
- Object.keys(FieldValuesForEdit).forEach(key => {
90
- result[DecodeFieldValuesAsTextKey(key)] = FieldValuesForEdit[key];
91
- });
92
- return result;
93
- }
94
-
95
- /** Get the field internal name as you can find it in the item[name] to get raw values */
96
- export function GetFieldNameFromRawValues(
97
- field: { InternalName: string; TypeAsString: FieldTypeAsString; },
98
- //ISSUE: 1250
99
- options: {
100
- excludeIdFromName: boolean
101
- } = {
102
- excludeIdFromName: false
103
- }): string {
104
- let fieldName = field.InternalName;
105
- if (options.excludeIdFromName !== true && (field.TypeAsString === "User" ||
106
- field.TypeAsString === "UserMulti" ||
107
- field.TypeAsString === "Lookup" ||
108
- field.TypeAsString === "LookupMulti" ||
109
- field.InternalName === "ContentType")) {
110
- fieldName = fieldName += "Id";
111
- }
112
-
113
- //issue 6698 fields that are too short will encode their first letter, and will start with _. this will add OData_ as a prefix in REST
114
- //Issue 336 _EndDate > OData__EndDate
115
- if (fieldName.startsWith('_')) {
116
- fieldName = "OData_" + fieldName;
117
- }
118
- return fieldName;
119
- }
120
-
121
- /** Get the field name to set on the item update REST request */
122
- export function getFieldNameForUpdate(field: IFieldInfoEX): string {
123
- if (field.TypeAsString === "TaxonomyFieldTypeMulti") {
124
- //Updating multi taxonomy value is allowed as string to the associated hidden text field
125
- return (field as IFieldTaxonomyInfo).HiddenMultiValueFieldName;
126
- }
127
-
128
- return GetFieldNameFromRawValues(field);
129
- }
130
-
131
- export function __isIRestError(e: any): e is IRestError {
132
- let x = e as IRestError;
133
- return !isNullOrUndefined(x) && !isNullOrUndefined(x.xhr) && isString(x.message);
134
- }
135
- /** extract the error message from a SharePoint REST failed request */
136
- export function __getSPRestErrorData(restError: IRestError) {
137
- let code = "Unknown";
138
- let errorMessage = "Unspecified error";
139
- if (restError && restError.message) errorMessage = restError.message;
140
- if (restError && restError.xhr && !isNullOrEmptyString(restError.xhr.responseText)) {
141
- let errorData = jsonParse<{ error: { code: string; message: { value: string; }; }; }>(restError.xhr.responseText);
142
- let error = errorData && errorData.error;
143
- if (!error && errorData)//in minimal rest - error is in "odata.error"
144
- error = errorData && errorData["odata.error"];
145
-
146
- if (error) {
147
- if (error && error.message && error.message.value)
148
- errorMessage = error.message.value;
149
- if (error && error.code)
150
- code = error.code;
151
- }
152
- }
153
- logger.error(errorMessage);
154
- return { code: code, message: errorMessage } as ISPRestError;
1
+ import { jsonParse } from "../../helpers/json";
2
+ import { isNullOrEmptyString, isNullOrUndefined, isString, isValidGuid } from "../../helpers/typecheckers";
3
+ import { makeServerRelativeUrl, normalizeUrl } from "../../helpers/url";
4
+ import { IDictionary } from "../../types/common.types";
5
+ import { IRestError } from "../../types/rest.types";
6
+ import { FieldTypeAsString, IFieldInfoEX, IFieldTaxonomyInfo } from "../../types/sharepoint.types";
7
+ import { ISPRestError } from "../../types/sharepoint.utils.types";
8
+ import { ConsoleLogger } from "../consolelogger";
9
+ import { getCacheItem, setCacheItem } from "../localstoragecache";
10
+ import { mediumLocalCache } from "../rest";
11
+ import { GetWebIdSync, GetWebInfoSync } from "./web";
12
+
13
+ const logger = ConsoleLogger.get("sharepoint.rest/common");
14
+
15
+ export const LIST_SELECT = `ListExperienceOptions,EffectiveBasePermissions,Description,Title,EnableAttachments,EnableModeration,BaseTemplate,BaseType,Id,Hidden,IsApplicationList,IsPrivate,IsCatalog,ImageUrl,ItemCount,ParentWebUrl,EntityTypeName,DefaultViewUrl,ParentWeb/Id,ParentWeb/Title`;
16
+ export const LIST_EXPAND = `ParentWeb/Id,ParentWeb/Title`;
17
+ export const WEB_SELECT = "Title,ServerRelativeUrl,Id,WebTemplate,Description,SiteLogoUrl";
18
+ export const CONTENT_TYPES_SELECT = "Name,Description,StringId,Group,Hidden,ReadOnly,NewFormUrl,DisplayFormUrl,EditFormUrl,Sealed,MobileDisplayFormUrl,MobileNewFormUrl,MobileEditFormUrl,NewFormTemplateName,DisplayFormTemplateName,EditFormTemplateName";
19
+ export const CONTENT_TYPES_SELECT_WITH_FIELDS = `${CONTENT_TYPES_SELECT},Fields`;
20
+
21
+ export function hasGlobalContext() {
22
+ //_spPageContextInfo.webServerRelativeUrl can be empty string
23
+ return typeof (_spPageContextInfo) !== "undefined" && isString(_spPageContextInfo.webServerRelativeUrl);
24
+ }
25
+
26
+ export function GetFileSiteUrl(fileUrl: string): string {
27
+ let siteUrl: string;
28
+ let urlParts = fileUrl.split('/');
29
+ if (urlParts[urlParts.length - 1].indexOf('.') > 0)//file name
30
+ urlParts.pop();//file name
31
+
32
+ let key = "GetSiteUrl|" + urlParts.join("/").toLowerCase();
33
+ siteUrl = getCacheItem<string>(key);
34
+ if (isNullOrUndefined(siteUrl)) {
35
+ while (!isValidGuid(GetWebIdSync(urlParts.join('/'))))
36
+ urlParts.pop();
37
+
38
+ siteUrl = normalizeUrl(urlParts.join('/'));
39
+ setCacheItem(key, siteUrl, mediumLocalCache.localStorageExpiration);//keep for 15 minutes
40
+ }
41
+ //must end with / otherwise root sites will return "" and we will think there is no site url.
42
+ return makeServerRelativeUrl(normalizeUrl(siteUrl, true));
43
+ }
44
+
45
+ /** gets a site URL or null, returns the current web URL or siteUrl as relative URL - end with /
46
+ * If you send a guid - it will look for a site with that ID in the current context site collection
47
+ */
48
+ export function GetSiteUrl(siteUrlOrId?: string): string {
49
+ let siteUrl: string;
50
+ if (isNullOrUndefined(siteUrlOrId)) {
51
+ if (hasGlobalContext()) {
52
+ siteUrl = _spPageContextInfo.webServerRelativeUrl;
53
+ if (_spPageContextInfo.isAppWeb)//#1300 if in a classic app sub-site
54
+ siteUrl = siteUrl.substring(0, siteUrl.lastIndexOf("/"));
55
+ }
56
+ else {
57
+ siteUrl = GetFileSiteUrl(window.location.pathname);
58
+ }
59
+ }
60
+ else if (isValidGuid(siteUrlOrId)) {
61
+ //GetWebInfoSync calls GetSiteUrl recursively, but with null should not get in here
62
+ let webInfo = GetWebInfoSync(null, siteUrlOrId);
63
+ siteUrl = webInfo.ServerRelativeUrl;
64
+ }
65
+ else siteUrl = siteUrlOrId;
66
+
67
+ //must end with / otherwise root sites will return "" and we will think there is no site url.
68
+ return makeServerRelativeUrl(normalizeUrl(siteUrl, true));
69
+ }
70
+
71
+ /** gets a site url, returns its REST _api url */
72
+ export function GetRestBaseUrl(siteUrl: string): string {
73
+ siteUrl = GetSiteUrl(siteUrl);
74
+ return siteUrl + '_api';
75
+ }
76
+
77
+ /** Get the field internal name as you can find it in item.FieldValuesAsText[name] (Or FieldValuesForEdit) */
78
+ export function DecodeFieldValuesAsTextKey(key: string): string {
79
+ return key.replace(/_x005f_/g, "_").replace('OData__', '_');
80
+ }
81
+
82
+ /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */
83
+ export function DecodeFieldValuesAsText(FieldValuesAsText: IDictionary<string>) {
84
+ return DecodeFieldValuesForEdit(FieldValuesAsText);
85
+ }
86
+ /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */
87
+ export function DecodeFieldValuesForEdit(FieldValuesForEdit: IDictionary<string>) {
88
+ let result: IDictionary<string> = {};
89
+ Object.keys(FieldValuesForEdit).forEach(key => {
90
+ result[DecodeFieldValuesAsTextKey(key)] = FieldValuesForEdit[key];
91
+ });
92
+ return result;
93
+ }
94
+
95
+ /** Get the field internal name as you can find it in the item[name] to get raw values */
96
+ export function GetFieldNameFromRawValues(
97
+ field: { InternalName: string; TypeAsString: FieldTypeAsString; },
98
+ //ISSUE: 1250
99
+ options: {
100
+ excludeIdFromName: boolean
101
+ } = {
102
+ excludeIdFromName: false
103
+ }): string {
104
+ let fieldName = field.InternalName;
105
+ if (options.excludeIdFromName !== true && (field.TypeAsString === "User" ||
106
+ field.TypeAsString === "UserMulti" ||
107
+ field.TypeAsString === "Lookup" ||
108
+ field.TypeAsString === "LookupMulti" ||
109
+ field.InternalName === "ContentType")) {
110
+ fieldName = fieldName += "Id";
111
+ }
112
+
113
+ //issue 6698 fields that are too short will encode their first letter, and will start with _. this will add OData_ as a prefix in REST
114
+ //Issue 336 _EndDate > OData__EndDate
115
+ if (fieldName.startsWith('_')) {
116
+ fieldName = "OData_" + fieldName;
117
+ }
118
+ return fieldName;
119
+ }
120
+
121
+ /** Get the field name to set on the item update REST request */
122
+ export function getFieldNameForUpdate(field: IFieldInfoEX): string {
123
+ if (field.TypeAsString === "TaxonomyFieldTypeMulti") {
124
+ //Updating multi taxonomy value is allowed as string to the associated hidden text field
125
+ return (field as IFieldTaxonomyInfo).HiddenMultiValueFieldName;
126
+ }
127
+
128
+ return GetFieldNameFromRawValues(field);
129
+ }
130
+
131
+ export function __isIRestError(e: any): e is IRestError {
132
+ let x = e as IRestError;
133
+ return !isNullOrUndefined(x) && !isNullOrUndefined(x.xhr) && isString(x.message);
134
+ }
135
+ /** extract the error message from a SharePoint REST failed request */
136
+ export function __getSPRestErrorData(restError: IRestError) {
137
+ let code = "Unknown";
138
+ let errorMessage = "Unspecified error";
139
+ if (restError && restError.message) errorMessage = restError.message;
140
+ if (restError && restError.xhr && !isNullOrEmptyString(restError.xhr.responseText)) {
141
+ let errorData = jsonParse<{ error: { code: string; message: { value: string; }; }; }>(restError.xhr.responseText);
142
+ let error = errorData && errorData.error;
143
+ if (!error && errorData)//in minimal rest - error is in "odata.error"
144
+ error = errorData && errorData["odata.error"];
145
+
146
+ if (error) {
147
+ if (error && error.message && error.message.value)
148
+ errorMessage = error.message.value;
149
+ if (error && error.code)
150
+ code = error.code;
151
+ }
152
+ }
153
+ logger.error(errorMessage);
154
+ return { code: code, message: errorMessage } as ISPRestError;
155
155
  }