@esri/solution-common
Version:
Provides general helper functions for @esri/solution.js.
448 lines (447 loc) • 15.9 kB
TypeScript
/** @license
* Copyright 2018 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides general helper functions.
*
* @module generalHelpers
*/
import { IModel } from "@esri/hub-common";
import { ICreateItemFromTemplateResponse, IDatasourceInfo, IItemTemplate, IStringValuePair } from "./interfaces";
import { Sanitizer } from "./libConnectors";
/**
* Returns a URL with a query parameter appended
*
* @param url URL to append to
* @param parameter Query parameter to append, prefixed with "?" or "&" as appropriate to what url already has
* @returns New URL combining url and parameter
*/
export declare function appendQueryParam(url: string, parameter: string): string;
/**
* Extracts JSON from a Blob.
*
* @param blob Blob to use as source
* @returns A promise that will resolve with JSON or null
*/
export declare function blobToJson(blob: Blob): Promise<any>;
/**
* Converts a Blob to a File.
*
* @param blob Blob to use as source
* @param filename Name to use for file
* @param mimeType MIME type to override blob's MIME type
* @returns File created out of Blob and filename
*/
export declare function blobToFile(blob: Blob, filename: string, mimeType?: string): File;
/**
* Extracts text from a Blob.
*
* @param blob Blob to use as source
* @returns A promise that will resolve with text read from blob
*/
export declare function blobToText(blob: Blob): Promise<string>;
/**
* Checks that a URL path ends with a slash.
*
* @param url URL to check
* @returns URL, appended with slash if missing
*/
export declare function checkUrlPathTermination(url: string): string;
/**
* Converts a hub-style item into a solutions-style item, the difference being handling of resources.
*
* @param hubModel Hub-style item
* @return solutions-style item
*/
export declare function convertIModel(hubModel: IModel | undefined): IItemTemplate;
/**
* Creates a random 32-character alphanumeric string.
*
* @returns A lowercase 32-char alphanumeric string
* @internal
*/
export declare function createLongId(): string;
/**
* Creates a random 8-character alphanumeric string that begins with an alphabetic character.
*
* @returns An alphanumeric string in the range [a0000000..zzzzzzzz]
*/
export declare function createShortId(): string;
/**
* Copies an input list removing duplicates.
*
* @param input List to be deduped
* @returns Deduped list; order of items in input is not maintained
*/
export declare function dedupe(input?: string[]): string[];
/**
* Performs an asynchronous delay.
*
* @param ms Milliseconds to delay
* @returns Promise when delay is complete
*/
export declare function delay(ms: number): Promise<unknown>;
/**
* Flags a failure to create an item from a template.
*
* @param itemType The AGO item type
* @param id Item id to include in response
* @returns Empty creation response
*/
export declare function generateEmptyCreationResponse(itemType: string, id?: string): ICreateItemFromTemplateResponse;
/**
* Generates a version 4 2-bit variant GUID.
*
* @returns A GUID
* @see {@link https://en.wikipedia.org/wiki/Universally_unique_identifier}, section "Version 4 (random)"
*/
export declare function generateGUID(): string;
/**
* Returns a regular expression matching a global search for a 32-character AGO-style id.
*
* @returns Regular expression
*/
export declare function getAgoIdRegEx(): RegExp;
/**
* Returns a regular expression matching a global search for a 32-character AGO-style id as a Solution template variable.
*
* @returns Regular expression
*/
export declare function getAgoIdTemplateRegEx(): RegExp;
/**
* Returns a regular expression matching a global search for a word such as an AGO-style id.
*
* @param word Word to search for, bounded by regular expression word boundaries (\b)
* @returns Regular expression
*/
export declare function getSpecifiedWordRegEx(word: string): RegExp;
/**
* Extracts templated ids from a block of text.
*
* @param text Text to scan for the pattern "{{[0-9A-F]{32}.itemId}}"
* @returns List of ids found in the text; braces and ".itemId" are removed; returns empty list if no matches
*/
export declare function getTemplatedIds(text: string): string[];
/**
* Converts JSON to a Blob.
*
* @param json JSON to use as source
* @returns A blob from the source JSON
*/
export declare function jsonToBlob(json: any): Blob;
/**
* Converts JSON to a File.
*
* @param json JSON to use as source
* @param filename Name to use for file
* @param mimeType MIME type to override blob's MIME type
* @returns File created out of JSON and filename
*/
export declare function jsonToFile(json: any, filename: string, mimeType?: string): File;
/**
* Makes a unique copy of JSON by stringifying and parsing.
*
* @param json JSON to use as source
* @returns A JSON object from the source JSON
*/
export declare function jsonToJson(json: any): any;
/**
* Saves a blob to a file.
*
* @param filename Name to give file
* @param blob Blob to save
* @returns Promise resolving when operation is complete
*/
export declare function saveBlobAsFile(filename: string, blob: Blob): Promise<void>;
/**
* Makes a deep clone, including arrays but not functions.
*
* @param obj Object to be cloned
* @returns Clone of obj
* @example
* ```js
* import { cloneObject } from "utils/object-helpers";
* const original = { foo: "bar" }
* const copy = cloneObject(original)
* copy.foo // "bar"
* copy === original // false
* ```
*/
export declare function cloneObject(obj: {
[index: string]: any;
}): any;
/**
* Compares two JSON objects using JSON.stringify.
*
* @param json1 First object
* @param json2 Second object
* @returns True if objects are the same
*/
export declare function compareJSON(json1: any, json2: any): boolean;
/**
* Compares two JSON objects using JSON.stringify, converting empty strings to nulls.
*
* @param json1 First object
* @param json2 Second object
* @returns True if objects are the same
*/
export declare function compareJSONNoEmptyStrings(json1: any, json2: any): boolean;
/**
* Compares two JSON objects property by property and reports each mismatch.
*
* @param json1 First object
* @param json2 Second object
* @returns A list of mismatch report strings
*/
export declare function compareJSONProperties(json1: any, json2: any): string[];
/**
* Sanitizes JSON and echoes changes to console.
*
* @param json JSON to sanitize
* @param sanitizer Instance of Sanitizer class
* @returns Sanitized version of `json`
* @see https://github.com/esri/arcgis-html-sanitizer#sanitize-json
*/
export declare function sanitizeJSONAndReportChanges(json: any, sanitizer?: Sanitizer): any;
export declare function deleteItemProps(itemTemplate: any): any;
/**
* Deletes a property from an object.
*
* @param obj Object with property to delete
* @param path Path into an object to property, e.g., "data.values.webmap", where "data" is a top-level property
* in obj
*/
export declare function deleteProp(obj: any, path: string): void;
/**
* Deletes properties from an object.
*
* @param obj Object with properties to delete
* @param props Array of properties on object that should be deleted
*/
export declare function deleteProps(obj: any, props: string[]): void;
/**
* Creates an AGO-style JSON failure response with success property.
*
* @param e Optional error information
* @returns JSON structure with property success set to false and optionally including `e`
*/
export declare function fail(e?: any): any;
/**
* Creates an AGO-style JSON failure response with success property and extended with ids list.
*
* @param ids List of ids
* @param e Optional error information
* @returns JSON structure with property success set to false and optionally including `e`
*/
export declare function failWithIds(itemIds: string[], e?: any): any;
/**
* Extracts subgroup ids from item tags
*
* @param tags Tags in an item
* @returns List of subgroup ids; subgroups are identified using tags that begin with "group." and end with a group id,
* e.g., "group.8d515625ee9f49d7b4f6c6cb2a389151"; non-matching tags are ignored
*/
export declare function getSubgroupIds(tags: string[]): string[];
/**
* Extracts the ids from a string
*
* @param v String to examine
* @returns List of id strings found
* @example
* get id from
* bad3483e025c47338d43df308c117308
* {bad3483e025c47338d43df308c117308
* =bad3483e025c47338d43df308c117308
* do not get id from
* http: *something/name_bad3483e025c47338d43df308c117308
* {{bad3483e025c47338d43df308c117308.itemId}}
* bad3483e025c47338d43df308c117308bad3483e025c47338d43df308c117308
*/
export declare function getIDs(v: string): string[];
/**
* Gets a property out of a deeply nested object.
* Does not handle anything but nested object graph
*
* @param obj Object to retrieve value from
* @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property
* in obj
* @returns Value at end of path
*/
export declare function getProp(obj: {
[index: string]: any;
}, path: string): any;
/**
* Returns an array of values from an object based on an array of property paths.
*
* @param obj Object to retrieve values from
* @param props Array of paths into the object e.g., "data.values.webmap", where "data" is a top-level property
* @returns Array of the values plucked from the object; only defined values are returned
*/
export declare function getProps(obj: any, props: string[]): any;
/**
* Get a property out of a deeply nested object
* Does not handle anything but nested object graph
*
* @param obj Object to retrieve value from
* @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property
* in obj
* @param defaultV Optional value to use if any part of path--including final value--is undefined
* @returns Value at end of path
*/
export declare function getPropWithDefault(obj: IStringValuePair, path: string, defaultV?: any): any;
/**
* Updates a list of the items dependencies if more are found in the
* provided value.
*
* @param v a string value to check for ids
* @param deps a list of the items dependencies
*/
export declare function idTest(v: any, deps: string[]): void;
/**
* Sets a deeply nested property of an object.
* Creates the full path if it does not exist.
*
* @param obj Object to set value of
* @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property in obj
* @param value The value to set at the end of the path
*/
export declare function setCreateProp(obj: any, path: string, value: any): void;
/**
* Sets a deeply nested property of an object.
* Does nothing if the full path does not exist.
*
* @param obj Object to set value of
* @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property in obj
* @param value The value to set at the end of the path
*/
export declare function setProp(obj: any, path: string, value: any): void;
/**
* Creates a timestamp string using the current UTC date and time.
*
* @returns Timestamp formatted as YYYYMMDD_hhmm_ssmmm, with month one-based and all values padded with zeroes on the
* left as needed (`ssmmm` stands for seconds from 0..59 and milliseconds from 0..999)
* @private
*/
export declare function getUTCTimestamp(): string;
/**
* Tests if an object's `item.typeKeywords` or `typeKeywords` properties has any of a set of keywords.
*
* @param jsonObj Object to test
* @param keywords List of keywords to look for in jsonObj
* @returns Boolean indicating result
*/
export declare function hasAnyKeyword(jsonObj: any, keywords: string[]): boolean;
/**
* Tests if an object's `item.typeKeywords` or `typeKeywords` properties has a specific keyword.
*
* @param jsonObj Object to test
* @param keyword Keyword to look for in jsonObj
* @returns Boolean indicating result
*/
export declare function hasTypeKeyword(jsonObj: any, keyword: string): boolean;
/**
* Will return the provided title if it does not exist as a property
* in one of the objects at the defined path. Otherwise the title will
* have a numerical value attached.
*
* @param title The root title to test
* @param templateDictionary Hash of the facts
* @param path to the objects to evaluate for potantial name clashes
* @returns string The unique title to use
*/
export declare function getUniqueTitle(title: string, templateDictionary: any, path: string): string;
/**
* Performs string replacement on every string in an object.
*
* @param obj Object to scan and to modify
* @param pattern Search pattern in each string
* @param replacement Replacement for matches to search pattern
* @returns Modified obj is returned
*/
export declare function globalStringReplace(obj: any, pattern: RegExp, replacement: string): any;
/**
* Tests if an array of DatasourceInfos has a given item and layer id already.
*
* @param datasourceInfos Array of DatasourceInfos to evaluate
* @param itemId The items id to check for
* @param layerId The layers id to check for
* @returns Boolean indicating result
*/
export declare function hasDatasource(datasourceInfos: IDatasourceInfo[], itemId: string, layerId: number): boolean;
/**
* remove templatization from item id to compare
*
* @example
* \{\{934a9ef8efa7448fa8ddf7b13cef0240.itemId\}\}
* returns 934a9ef8efa7448fa8ddf7b13cef0240
*/
export declare function cleanItemId(id: any): any;
/**
* remove templatization from layer based item id to compare
*
* @example
* \{\{934a9ef8efa7448fa8ddf7b13cef0240.layer0.itemId\}\}
* returns 934a9ef8efa7448fa8ddf7b13cef0240
*/
export declare function cleanLayerBasedItemId(id: any): any;
/**
* remove templatization from layer id to compare
*
* @example
* \{\{934a9ef8efa7448fa8ddf7b13cef0240.layer0.layerId\}\}
* returns 0
*/
export declare function cleanLayerId(id: any): any;
/**
* Get template from list of templates by ID
*
* @param templates Array of item templates to search
* @param id of template we are searching for
*
* @returns Template associated with the user provided id argument
*/
export declare function getTemplateById(templates: IItemTemplate[], id: string): any;
/**
* Evaluates a value with a regular expression
*
* @param v a string value to test with the expression
* @param ex the regular expresion to test with
* @returns an array of matches
*/
export declare function regExTest(v: any, ex: RegExp): any[];
/**
* Removes duplicates from a list of strings.
*
* @param list List to be de-duped
* @returns List of unique strings
*/
export declare function uniqueStringList(list: string[]): string[];
/**
* Creates a random number between two values.
*
* @param min Inclusive minimum desired value
* @param max Non-inclusive maximum desired value
* @returns Random number in the range [min, max)
*/
export declare function _getRandomNumberInRange(min: number, max: number): number;
/**
* Pads the string representation of a number to a minimum width. Requires modern browser.
*
* @param n Number to pad
* @param totalSize Desired *minimum* width of number after padding with zeroes
* @returns Number converted to string and padded on the left as needed
* @private
*/
export declare function _padPositiveNum(n: number, totalSize: number): string;