squared

setHostname(value)

Use another CORS-enabled server for processing assets.

Parameters:

value (string) – http(s)://hostname(:port)

Usage:

squared.setHostname("https://localhost:8000");

squared.setHostname(); // Reset to window.location (e.g. localhost:3000)
setEndpoint(name, value)

Set alternate pathname for API v1 functions.

Parameters:
  • name (string) – “ASSETS_COPY” or “ASSETS_ARCHIVE” or “LOADER_DATA” or “THREADS_KILL” or “WEBSOCKET_OBSERVE”

  • value (string) – Absolute path to server GET/POST method

Usage:

squared.setEndpoint("ASSETS_COPY", "/api/v2/assets/copy");
setLocalAddress(...values)

Additional hostnames which are interpreted as localhost. Protocol and port are not required.

Parameters:

values (string) – Same format as URL.hostname

Usage:

squared.setLocalAddress("127.0.0.1", "nodejs-001");

Alternate:

squared.setLocalAddress(new URL("http://0.0.0.0"));
auth(token[, credentials])

Use a JWT header authorization token for all outgoing requests. Custom service providers are supported by passing a credentials object.

Parameters:
  • token (string or boolean) – Three concatenated Base64url-encoded strings separated by dots

  • credentials (object) – Serialize object as auth property

Usage:

squared.auth("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNxdWFyZWQiLCJwYXNzd29yZCI6Imp3dDEyMyIsImlhdCI6MTY1MjcxNDQwMH0.xqwQ96LsItilsB1dskzJQqXORaZ4mGMu0FeZezo297c");

Alternate:

squared.auth(true, { username: "mongo", password: "89064", realm: "hokkaido" }); // { auth: undefined }
squared.auth("chrome", { username: "redis", password: "1022", realm: "tohoku" }); // { auth: "chrome" }
squared.auth({ default: {/* Same */}, chrome: {/* Same */} });
kill([pid, timeout])

Abort request if not completed in the given amount of time.

Parameters:
  • pid (number) – File request self-assigned number (options.pid)

  • timeout (number) – Seconds until request expires

Returns:

PID of 1 or greater when successful

Return type:

Promise<number>

Usage:

squared.saveAs("example.zip", { pid: 100 });
squared.kill(100).then(result => {
  if (result > 0) {
    /* KILLED */
  }
});

squared.kill(); // Terminate previous request
squared.kill(0); // By username (auth required)

squared.kill(-1, 10); // Terminate previous request in 10 seconds
squared.kill(NaN, 0.5); // Terminate next request in 500 milliseconds

Alternate:

squared.kill(-1, "10s"); // Terminate previous request in 10 seconds
squared.kill("500ms"); // Terminate next request in 500 milliseconds
broadcast(callback, socketId)

Redirect stdout messages to DevTools console.

Parameters:
  • callback (BroadcastMessageCallback) – Void function for incoming data

  • socketId (string) – Unique identifier assigned during server initialization

Returns:

Success when connection established

Return type:

boolean

Usage:

squared.broadcast(result => { console.log(result.value); }, "111-111-111"); // Uses "socketId"
squared.broadcast(result => { console.log(result.value); }, "222-222-222");

squared.copyTo("/path/to/project", { broadcastId: ["111-111-111", "222-222-222"] });

Alternate:

squared.copyTo("/path/to/project", {
  broadcast: {
    socketId: "111-111-111",
    callback: result => {
      console.log(result.value);
    }
  }
});

// Messages sent from another API (FileBroadcastOptions)
squared.broadcast(result => { console.log(result.value); }, { // Uses "socket_id"
  socketId: "333-333-333",
  socketKey: "socket_id",
  secure: true,
  hostname: "1.1.1.1",
  port: 8080
});
setFramework(target[, options, cache])

Install application interpreter. (e.g. android.framework.js)

Parameters:
  • target (AppFramework) – Global object implementation of base functionality

  • options (object) – Initialize settings with non-default values

  • cache (boolean) – Load previous cached instance and settings

Usage:

squared.setFramework(android);
squared.setFramework(android, true); // Used when switching frameworks
squared.setFramework(android, { targetAPI: 35, idNamingStyle: "html" });

Alternate:

// Save
squared.setFramework(android, { targetAPI: 26, enabledIncludes: true }, "example"); // Local storage

// Load
squared.setFramework(android, "example");
extend(map[, framework])

Add functions and initial variables to the Node prototype including overwriting preexisting class definitions. Accessor properties are supported using the get/set object syntax.

Parameters:
  • map (object) – Attribute object consisting of extensions and overrides

  • framework (APP_FRAMEWORK) – Bit mask of supported frameworks

Usage:

squared.extend({
  _id: 1,
  altId: {
    get() {
      return this._id;
    },
    set(value) {
      this._id += value;
    }
  },
  customId: {
    value: 2,
    configurable: false,
    enumerable: false
  },
  addEvent(eventName, callback) {
    this.element.addEventListener(eventName, callback);
  }
});
squared.setFramework(vdom);

const body = await squared.fromElement(document.body);
body.altId = 2; // 3
body.altId = 2; // 5
body.addEvent("click", function (ev) {
  this.classList.toggle("example");
});

squared.extend({ _preferInitial: true }, APP_FRAMEWORK.VDOM /* 1 */ | APP_FRAMEWORK.CHROME /* 4 */); // squared.base.lib.constant
squared.setFramework(chrome);
clear()

Calls Application.clear() for any loaded frameworks and deletes all cached sessions.

Usage:

squared.clear();
add(...targets)

Include extensions to be processed with any built-in extensions.

Parameters:

targets (string or Extension or [string | Extension, object]) – Name of disabled extension or control implementing Extension. With a configuration object use a tuple wrapper.

Returns:

Number of extensions to be installed

Return type:

number

Usage:

class Drawer extends squared.base.ExtensionUI {
  constructor(name, framework, options) {
    super(name, framework, options);
    this.options = {
      element: {},
      resource: {},
      self: {},
      navigationView: {}
    };
    this.documentBase = true;
    this.require({ name: "android.external", leading: true });
    this.require("android.widget.menu");
    this.require("android.widget.coordinator");
  }
}

const drawer = new Drawer("android.widget.drawer", squared.base.lib.constant.APP_FRAMEWORK.ANDROID /* 2 */);
squared.add(drawer);

// Built-in
squared.add("android.resource.includes");

const options = {
  element: {
    content: { android: { layout_width: "match_parent" } }
  }
};
squared.add(["android.substitute", options]);
remove(...targets)

Exclude extensions by name or control.

Parameters:

targets – Name or control of extensions

Returns:

Number of extensions removed

Return type:

number

Usage:

const drawer = new Drawer("android.widget.drawer", 2);
squared.add(drawer);

squared.remove(drawer);
/* OR */
squared.remove("android.widget.drawer");
get(...targets)

Retrieve extensions by name only.

Parameters:

targets (string) – Name of extension

Returns:

Installed extensions in current framework

Return type:

Usage:

const drawer = squared.get("android.widget.drawer");
const [drawer, menu] = squared.get("android.widget.drawer", "android.widget.menu");

drawer.options.navigationView.android = { fitsSystemWindows: "true" };
menu.project.set(document.getElementId("child-item-id"), await fetch("http://localhost:3000/drawer/menu.json"), "project-1" /* optional */); // Add project data
attr(target, name[, value, append])

Set or get extension options. typeof is enforced and will only set existing attributes.

Parameters:
  • target – Name or control of extension

  • name (string) – Name of attribute in Extension.options

  • value – Any value of an existing attribute

  • append (boolean) – Any value of an existing attribute

Returns:

Resultant value of attempted action

Return type:

unknown

Usage:

const items = squared.attr("android.substitute", "viewAttributes" /* string[] */);
items.push("hint", "buttonTint");
/* OR */
squared.attr("android.substitute", "viewAttributes", items.concat(["hint", "buttonTint"]));

squared.attr("android.substitute", "attributeMapping", { "android:src": "app:srcCompat", "icon": "navigationIcon" }); // Set only and does not merge

Alternate:

squared.attr("android.resource.styles", "inheritFromParent", { "Text_P": "TextAppearance.AppCompat" }, true); // Assigns objects and concats arrays
apply(target, options[, setting])

Find extension and merge a configuration object with existing Extension.options.

Parameters:
  • target – Name or control of extension

  • options (object) – Overriding configuration values

  • setting (string) – Name to use when saving to local storage

Returns:

Success when modified

Return type:

boolean

Usage:

squared.apply("android.widget.toolbar", {
  element: {
    "toolbar-id": {
      android: {
        background: "?android:attr/windowBackground"
      },
      appBar: {
        android: {
          theme: "@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        }
      }
    }
  },
  "toolbar-example" // Save
});

Alternate:

squared.apply("android.widget.toolbar", "toolbar-example"); // Load
prefetch(type[, all, ...targets])

Downloads assets to a memory cache which can be used by an Application framework. Provides cross-origin support for CSS.

Parameters:
  • type (string) – css or javascript or image or svg

  • all (boolean) – (optional) Accept request from any origin

  • targets (string or Element) – URL string or root element of a contained Document

Returns:

Data as string or Blob of each resource

Return type:

Promise<PrefetchItem[]>

Usage:

squared.prefetch("css").then(() => squared.parseDocument()); // Cross-origin support

Promise.all(
  squared.prefetch("css", true), // All stylesheets
  squared.prefetch("css", "./undetected.css", document.getElementById("shadow-id").shadowRoot),
  squared.prefetch("svg", "http://example.com/icon.svg", "../images/android.svg")
)
.then(() => squared.parseDocument());
parseDocument(...elements)

Starts at the root target element and creates a virtual DOM structure by cascading into all the children. Assets can be preloaded (e.g. images) which is required with the android framework.

Parameters:

elements (string or HTMLElement or ElementSettings) – Element target by either an id string or HTMLElement

Returns:

Root element of document as Node instance

Return type:

  • Promise<Node> or Promise<void>

  • Promise<Node[]> (multiple)

Usage:

const body = await squared.parseDocument();

const section = await squared.parseDocument({
  element: "section-1",
  projectId: "sqd",
  resourceQualifier: "land",
  enabledIncludes: true
});
parseDocumentSync(...elements)

Starts at the root target element and creates a virtual DOM structure by cascading into all the children. No assets are preloaded which is sufficient for the vdom framework.

Parameters:

elements (string or HTMLElement or ElementSettings) – Element target by either an id string or HTMLElement

Returns:

Root element of document as Node instance

Return type:

Usage:

const body = squared.parseDocumentSync();

const content = squared.parseDocumentSync("content-1");
findDocumentNode(target[, all, projectId])

Can be used before saving rendered document to modify auto-generated Node attributes.

Parameters:
  • targetElement target by either an id string or HTMLElement (selectors are supported)

  • all (boolean) – (optional) Uses filter to return multiple results

  • projectId (string) – Uses an existing project in the current framework

Returns:

Target element(s) as Node instance

Return type:

Usage:

const body = squared.findDocumentNode(document.body);
const content = squared.findDocumentNode("content-1");

const section1 = squared.findDocumentNode("section"); // Only if no element has id="section"
const [section2, section3] = squared.findDocumentNode("main > section", true); // Always an array with "all"

Alternate:

const layout = squared.findDocumentNode("relativelayout-1", "project-1"); // Control id
layout.android("layout_width", "match_parent");
latest([count=1])

Get any stored session ids from parseDocument() since the last time clear() was called.

Parameters:

count (number) – How many ids at most to be retrieved

Returns:

List of sequential ids

Return type:

string or string[] or undefined

Usage:

squared.parseDocument("id-1", "id-2", "id-3").then(() => {
  // ["00001", "00002", "00003"]
  const id3 = squared.latest();
  const id1 = squared.latest(-1);
  const [id2, id3] = squared.latest(2);
  const [id2, id1] = squared.latest(-2);
});
close([projectId])

Ends the current session or selected project preventing any further modifications. It is called internally when saving or copying.

Parameters:

projectId (string) – Targets a project that is not the latest

Returns:

Success when in finalizable state

Return type:

Promise<boolean>

Usage:

await squared.close(); // Optional
reset([projectId])

Abandons all stored projects and sets a loaded Application to its initial state. The current user settings are retained.

Parameters:

projectId (string) – Targets a project that is not the latest

Usage:

squared.reset(); // Optional
save([projectId, timeout])

Uses the default Application.settings to generate an archive of the current session or selected project.

Parameters:
  • projectId (string) – Targets a project that is not the default project

  • timeout (number) – Maximum time in seconds for build to complete

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

squared.save().then(result => console.log(result)); // Default project "_" is used

await squared.save("project-1", 10); // 10 seconds for "project-1" to build

Alternate:

squared.broadcast(result => { console.log(result.value); }, "111-111-111");
await squared.save("project-1", "111-111-111"); // broadcastId
saveAs(filename[, options, setting, overwrite])

Save current session or selected project as a new archive using filename extension.

Parameters:
  • filename (string) – Name of file with a valid archive extension

  • options (FileActionOptions) – Object of framework specific functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

await squared.parseDocument();
await squared.saveAs("android.zip", { timeout: 15, log: { showSize: true } }); // Uses default unnamed project "_"

await squared.parseDocument({ element: document.body, projectId: "project-1" });
await squared.saveAs("project-1.7z", { projectId: "project-1", throwErrors: true }).catch(err => { // Will cancel partial archive download
  console.log(err);
});

Alternate:

// Save
squared.saveAs("android.zip", { timeout: 15, log: { showSize: true } }, "android-example"); // Uses own "saveAs" namespace

// Load
squared.saveAs("android.zip", "android-example"); // Any page in same domain
appendTo(uri[, options, setting, overwrite])

Save current session or selected project into a copy of an existing archive if found or as a new archive using the file extension.

Parameters:
  • uri (string) – Location of file with a valid archive extension

  • options (FileActionOptions) – Object of framework specific functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

squared.parseDocument().then(async () => {
  await squared.appendTo("http://localhost:3000/archives/android.001", { format: "tar" }); // "tar" is explicit (ignored filename)
});

await squared.parseDocument({ element: document.body, projectId: "project-1" });
squared.appendTo("../data/project-1.7z", { projectId: "project-1" }).then(result => { // Uses NodeJS process.cwd() resolution
  console.log(result);
});

Alternate:

// Save
squared.appendTo("./android.zip", { timeout: 20, log: { showSize: true } }, "android-example"); // Uses own "appendTo" namespace

// Load
squared.appendTo("./android.zip", "android-example"); // Any page in same domain
copyTo(pathname[, options, setting, overwrite])

Save current session or selected project to a local directory.

Parameters:
  • pathname (string) – Location of a directory accessible to the server process

  • options (FileActionOptions) – Object of framework specific functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

await squared.parseDocument();
await squared.copyTo("./path/to/project", { timeout: 10, log: { showSize: true } });

squared.parseDocument({ element: document.body, projectId: "project-1" }).then(() => {
  squared.copyTo("/path/project", { projectId: "project-1" }).then(result => console.log(result));
});

Alternate:

// Multiple
squared.copyTo(["/path/project1", "/path/project2"]); // Copies processed files to "project1" and "project2"

// Save
squared.copyTo("./path/to/project", { timeout: 10, log: { showSize: true } }, "android-example"); // Uses own "copyTo" namespace

// Load
squared.copyTo("./path/to/project", "android-example"); // Any page in same domain
saveFiles(filename[, options, setting, overwrite])

Save selected assets as a new archive using filename extension.

Parameters:
  • filename (string) – Name of file with a valid archive extension

  • options (FileActionOptions) – Object of file saving functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

const options = {
  assets: [
    {
      pathname: "images",
      filename: "android.png",
      uri: "http://localhost:3000/common/images/android.png" // ./images/android.png
    },
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-ldpi.png", // ./images/android-ldpi.png
      document: undefined
    },
    {
      uri: "http://localhost:3000/common/images/android-hdpi.png", // ./android-hdpi.png
      document: undefined
    }
  ]
};
await squared.saveFiles("android.zip", options);

Alternate:

// Save
squared.saveFiles("android.zip", options, "android-example"); // Uses own "saveFiles" namespace

// Load
squared.saveFiles("android.zip", "android-example"); // Any page in same domain
appendFiles(uri[, options, setting, overwrite])

Save selected assets into a copy of an existing archive if found or as a new archive using the file extension.

Parameters:
  • uri (string) – Location of file with a valid archive extension

  • options (FileActionOptions) – Object of file appending functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

const options = {
  format: "7z",
  assets: [
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xhdpi.png"
    },
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xxhdpi.png"
    },
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xxxhdpi.png"
    }
  ]
};
await squared.appendFiles("http://localhost:3000/archives/android.001", options);

Alternate:

// Save
squared.appendFiles("android.zip", options, "android-example"); // Uses own "appendFiles" namespace

// Load
squared.appendFiles("android.zip", "android-example"); // Any page in same domain
copyFiles(pathname[, options, setting, overwrite])

Save selected assets to a local directory.

Parameters:
  • pathname (string) – Location of a directory accessible to the server process

  • options (FileActionOptions) – Object of file copying functionality to be applied

  • setting (string) – Name of setting for local storage

  • overwrite (boolean) – Will not merge previously saved settings with options

Returns:

Server response of requested action

Return type:

Promise<ResponseData>

Usage:

const options = {
  assets: [
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xhdpi.png"
    },
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xxhdpi.png"
    },
    {
      pathname: "images",
      uri: "http://localhost:3000/common/images/android-xxxhdpi.png"
    }
  ]
};
await squared.copyFiles("/path/project", options);

Alternate:

// Multiple
squared.copyFiles(["/path/project1", "/path/project2"], options); // Copies assets to "project1" and "project2"

// Save
squared.copyFiles("./path/to/project", options, "android-example"); // Uses own "copyFiles" namespace

// Load
squared.copyFiles("./path/to/project", "android-example"); // Any page in same domain
toString([projectId])

Writes the system name of the currently installed non-UI framework.

Parameters:

projectId (string) – Targets a project that is not the default project

Returns:

Framework defined (UI) or system name

Return type:

string

Usage:

squared.setFramework(chrome);
const systemName = squared.toString(); // "chrome"

Alternate:

squared.setFramework(android);
await squared.parseDocument();
await squared.close();
const activityMain = squared.toString("project1"); // XML content
getElementById(value[, sync, cache=true])

Same behavior as native document.getElementById [1] except returns a Node instance.

Parameters:
  • value (string) – Case-sensitive match against Element.id property

  • sync (boolean) – Will block and not wrap query in a Promise

  • cache (boolean) – Use any existing Node instance of Element

Returns:

Target element(s) as Node instance

Return type:

  • Promise<Node> or Promise<null>

  • Node or null (sync)

Usage:

const { element, attributes } = await squared.getElementById("content-id");

const content = squared.getElementById("content-id", true); // Synchronous
const child = content?.find(item => item.elementId === "child-id", { cascade: true });
querySelector(selector[, sync, cache=true])

Same behavior as native document.querySelector [2] except returns a Node instance.

Parameters:
  • selector (string) – Selector or selectors matching one or more elements

  • sync (boolean) – Will block and not wrap query in a Promise

  • cache (boolean) – Use any existing Node instance of Element

Returns:

Target element(s) as Node instance

Return type:

  • Promise<Node> or Promise<null>

  • Node or null (sync)

Usage:

const { element, attributes } = await squared.querySelector("section img[src=vdom.png]");

squared.querySelector("body > p", true)?.each(item => { // Synchronous
  if (item.inline) {
    item.css("display", "inline-block");
  }
});
querySelectorAll(selector[, sync, cache=true])

Same behavior as native document.querySelectorAll [3] except returns an array of Node instances.

Parameters:
  • selector (string) – Selector or selectors matching one or more elements

  • sync (boolean) – Will block and not wrap query in a Promise

  • cache (boolean) – Use any existing Node instance of Element

Returns:

Target element(s) as Node instance

Return type:

  • Promise<Node[]> or Promise<null>

  • Node[] or null (sync)

Usage:

const [img1, img2] = await squared.querySelectorAll("section img");

const children = await squared.getElementById("content-id")?.querySelectorAll("*");
fromElement(element[, sync, cache])

Same behavior as getElementById() except it also accepts a native Element. The cache parameter by default is not enabled.

Parameters:
  • elementElement target by either an id string or HTMLElement

  • sync (boolean) – Will block and not wrap query in a Promise

  • cache (boolean) – Use any existing Node instance of Element

Returns:

Target element(s) as Node instance

Return type:

  • Promise<Node> or Promise<null>

  • Node or null (sync)

Usage:

const { element, attributes } = await squared.fromElement(document.body);

const content = squared.fromElement("content-id", true); // Synchronous
const child = content?.find(item => item.elementId === "child-id", { cascade: true });
fromNode(node[, sync, cache])

Uses an existing Node instance and creates a new instance with any modifications. The cache parameter by default is not enabled.

Parameters:
  • node (Node) – Reference to a Node

  • sync (boolean) – Will block and not wrap query in a Promise

  • cache (boolean) – Use any existing Node instance

Returns:

Target element(s) as Node instance

Return type:

  • Promise<Node> or Promise<null>

  • Node or null (sync)

Usage:

let body = await squared.fromElement(document.body);
document.querySelectorAll("body div").forEach(item => document.body.removeChild(item));
body = await squared.fromNode(body);

const img = squared.fromNode(body, true).find(item => item.imageElement); // Synchronous
observe([enable=true])

Uses MutationObserver to watch for any changes to the parseDocument() root element. Start after DOM and third-party libraries are initialized.

Parameters:

enable (boolean) – Start or stop all root elements who are monitoring

Usage:

await squared.parseDocument({
  element: document.body,
  projectId: "project-1",
  observe(mutations, observer, settings) {
    squared.reset("project-1");
    squared.parseDocument(settings).then(() => {
      squared.copyTo("/path/project", { projectId: "project-1", modified: true }).then(result => console.log(result));
    });
  }
});

await squared.copyTo("/path/project", { projectId: "project-1", useOriginalHtmlPage: false }).then(() => {
  squared.observe();
});

squared.observe(false); // Discontinue monitoring for changes

Alternate:

squared.observe({
  subtree: true,
  childList: true,
  attributes: true,
  characterData: false,
  attributeOldValue: false,
  characterDataOldValue: false
});
observeSrc(targets, [callback, ]options)

Can be used to watch external elements which contain modifiable source files.

Parameters:
  • targets – Elements by either selector or HTMLElement (src or href attribute is required)

  • callback (WebSocketMessageChange) – (optional) Function to call when a modified event is received

  • options (FileObserveOptions) – Connection attributes overrides sent to server

Returns:

Connected locations with external source

Return type:

Promise<ObserveSocket> or Promise<ObserveSocket[]>

Usage:

const settings = { element: document.body, projectId: "project-1" };
squared.parseDocument(settings).then(() => {
  squared.observeSrc(
    "link[rel=stylesheet]",
    (ev, element) => {
      squared.reset("project-1");
      squared.parseDocument(settings).then(() => squared.copyTo("/path/project"));
    },
    { port: 8080, secure: false, action: "reload", expires: "1h" } // Optional
  );
});

Alternate:

await squared.observeSrc("link[rel=stylesheet]"); // Will call location.reload()