summaryrefslogtreecommitdiffstats
path: root/devtools/client/jsonview
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 17:32:43 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 17:32:43 +0000
commit6bf0a5cb5034a7e684dcc3500e841785237ce2dd (patch)
treea68f146d7fa01f0134297619fbe7e33db084e0aa /devtools/client/jsonview
parentInitial commit. (diff)
downloadthunderbird-upstream.tar.xz
thunderbird-upstream.zip
Adding upstream version 1:115.7.0.upstream/1%115.7.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'devtools/client/jsonview')
-rw-r--r--devtools/client/jsonview/.eslintrc.js15
-rw-r--r--devtools/client/jsonview/Converter.sys.mjs17
-rw-r--r--devtools/client/jsonview/Sniffer.sys.mjs64
-rw-r--r--devtools/client/jsonview/components.conf26
-rw-r--r--devtools/client/jsonview/components/Headers.js118
-rw-r--r--devtools/client/jsonview/components/HeadersPanel.js56
-rw-r--r--devtools/client/jsonview/components/HeadersToolbar.js51
-rw-r--r--devtools/client/jsonview/components/JsonPanel.js163
-rw-r--r--devtools/client/jsonview/components/JsonToolbar.js92
-rw-r--r--devtools/client/jsonview/components/LiveText.js43
-rw-r--r--devtools/client/jsonview/components/MainTabbedArea.js120
-rw-r--r--devtools/client/jsonview/components/SearchBox.js102
-rw-r--r--devtools/client/jsonview/components/TextPanel.js52
-rw-r--r--devtools/client/jsonview/components/TextToolbar.js80
-rw-r--r--devtools/client/jsonview/components/moz.build20
-rw-r--r--devtools/client/jsonview/components/reps/Toolbar.js48
-rw-r--r--devtools/client/jsonview/components/reps/moz.build9
-rw-r--r--devtools/client/jsonview/converter-child.js419
-rw-r--r--devtools/client/jsonview/css/general.css48
-rw-r--r--devtools/client/jsonview/css/headers-panel.css66
-rw-r--r--devtools/client/jsonview/css/json-panel.css18
-rw-r--r--devtools/client/jsonview/css/main.css44
-rw-r--r--devtools/client/jsonview/css/moz.build15
-rw-r--r--devtools/client/jsonview/css/search-box.css20
-rw-r--r--devtools/client/jsonview/css/text-panel.css18
-rw-r--r--devtools/client/jsonview/css/toolbar.css39
-rw-r--r--devtools/client/jsonview/json-viewer.js203
-rw-r--r--devtools/client/jsonview/lib/moz.build7
-rw-r--r--devtools/client/jsonview/lib/require.js2080
-rw-r--r--devtools/client/jsonview/moz.build24
-rw-r--r--devtools/client/jsonview/test/array_json.json1
-rw-r--r--devtools/client/jsonview/test/array_json.json^headers^1
-rw-r--r--devtools/client/jsonview/test/browser.ini59
-rw-r--r--devtools/client/jsonview/test/browser_json_refresh.js97
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_bug_1380828.js32
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_chunked_json.js121
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_content_type.js100
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_copy_headers.js38
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_copy_json.js34
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js62
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_csp_json.js33
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_data_blocking.js174
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_empty_object.js48
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_encoding.js67
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_expand_collapse.js61
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_filter.js27
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_filter_clear.js85
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_ignore_charset.js18
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_initial_focus.js33
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_invalid_json.js18
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_manifest.js15
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_nojs.js26
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_nul.js15
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_object-type.js25
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_row_selection.js245
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_save_json.js159
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_serviceworker.js89
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_slash.js16
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_theme.js29
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_url_linkification.js88
-rw-r--r--devtools/client/jsonview/test/browser_jsonview_valid_json.js46
-rw-r--r--devtools/client/jsonview/test/chunked_json.sjs39
-rw-r--r--devtools/client/jsonview/test/csp_json.json1
-rw-r--r--devtools/client/jsonview/test/csp_json.json^headers^2
-rw-r--r--devtools/client/jsonview/test/empty.html1
-rw-r--r--devtools/client/jsonview/test/head.js278
-rw-r--r--devtools/client/jsonview/test/invalid_json.json1
-rw-r--r--devtools/client/jsonview/test/invalid_json.json^headers^1
-rw-r--r--devtools/client/jsonview/test/manifest_json.json49
-rw-r--r--devtools/client/jsonview/test/manifest_json.json^headers^1
-rw-r--r--devtools/client/jsonview/test/passthrough-sw.js5
-rw-r--r--devtools/client/jsonview/test/simple_json.json1
-rw-r--r--devtools/client/jsonview/test/simple_json.json^headers^1
-rw-r--r--devtools/client/jsonview/test/valid_json.json6
-rw-r--r--devtools/client/jsonview/test/valid_json.json^headers^1
-rw-r--r--devtools/client/jsonview/viewer-config.js46
76 files changed, 6372 insertions, 0 deletions
diff --git a/devtools/client/jsonview/.eslintrc.js b/devtools/client/jsonview/.eslintrc.js
new file mode 100644
index 0000000000..cd16102c98
--- /dev/null
+++ b/devtools/client/jsonview/.eslintrc.js
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+module.exports = {
+ globals: {
+ define: true,
+ document: true,
+ window: true,
+ CustomEvent: true,
+ JSONView: true,
+ },
+};
diff --git a/devtools/client/jsonview/Converter.sys.mjs b/devtools/client/jsonview/Converter.sys.mjs
new file mode 100644
index 0000000000..560f82440a
--- /dev/null
+++ b/devtools/client/jsonview/Converter.sys.mjs
@@ -0,0 +1,17 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Create instances of the JSON view converter.
+ */
+export function Converter() {
+ const { require } = ChromeUtils.importESModule(
+ "resource://devtools/shared/loader/Loader.sys.mjs"
+ );
+ const {
+ JsonViewService,
+ } = require("resource://devtools/client/jsonview/converter-child.js");
+
+ return JsonViewService.createInstance();
+}
diff --git a/devtools/client/jsonview/Sniffer.sys.mjs b/devtools/client/jsonview/Sniffer.sys.mjs
new file mode 100644
index 0000000000..d585ce8ab2
--- /dev/null
+++ b/devtools/client/jsonview/Sniffer.sys.mjs
@@ -0,0 +1,64 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
+
+const gPrefs = {};
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ gPrefs,
+ "gEnabled",
+ "devtools.jsonview.enabled"
+);
+
+const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view";
+
+function getContentDisposition(channel) {
+ try {
+ return channel.contentDisposition;
+ } catch (e) {
+ // Channel doesn't support content dispositions
+ return null;
+ }
+}
+
+/**
+ * This component represents a sniffer (implements nsIContentSniffer
+ * interface) responsible for changing top level 'application/json'
+ * document types to: 'application/vnd.mozilla.json.view'.
+ *
+ * This internal type is consequently rendered by JSON View component
+ * that represents the JSON through a viewer interface.
+ *
+ * This is done in the .js file rather than a .jsm to avoid creating
+ * a compartment at startup when no JSON is being viewed.
+ */
+export class Sniffer {
+ getMIMETypeFromContent(request, data, length) {
+ if (request instanceof Ci.nsIChannel) {
+ // JSON View is enabled only for top level loads only.
+ if (
+ gPrefs.gEnabled &&
+ request.loadInfo?.isTopLevelLoad &&
+ request.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI &&
+ getContentDisposition(request) != Ci.nsIChannel.DISPOSITION_ATTACHMENT
+ ) {
+ // Check the response content type and if it's a valid type
+ // such as application/json or application/manifest+json
+ // change it to new internal type consumed by JSON View.
+ if (/^application\/(?:.+\+)?json$/.test(request.contentType)) {
+ return JSON_VIEW_MIME_TYPE;
+ }
+ } else if (request.contentType === JSON_VIEW_MIME_TYPE) {
+ return "application/json";
+ }
+ }
+
+ return "";
+ }
+}
+
+Sniffer.prototype.QueryInterface = ChromeUtils.generateQI([
+ "nsIContentSniffer",
+]);
diff --git a/devtools/client/jsonview/components.conf b/devtools/client/jsonview/components.conf
new file mode 100644
index 0000000000..e4fc8ba458
--- /dev/null
+++ b/devtools/client/jsonview/components.conf
@@ -0,0 +1,26 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view"
+
+Classes = [
+ {
+ 'cid': '{4148c488-dca1-49fc-a621-2a0097a62422}',
+ 'contract_ids': ['@mozilla.org/devtools/jsonview-sniffer;1'],
+ 'esModule': 'resource://devtools/client/jsonview/Sniffer.sys.mjs',
+ 'constructor': 'Sniffer',
+ 'categories': {
+ 'net-content-sniffers': 'JSONView',
+ 'net-and-orb-content-sniffers': 'JSONView',
+ },
+ },
+ {
+ 'cid': '{d8c9acee-dec5-11e4-8c75-1681e6b88ec1}',
+ 'contract_ids': ['@mozilla.org/streamconv;1?from=%s&to=*/*' % JSON_VIEW_MIME_TYPE],
+ 'esModule': 'resource://devtools/client/jsonview/Converter.sys.mjs',
+ 'constructor': 'Converter',
+ },
+]
diff --git a/devtools/client/jsonview/components/Headers.js b/devtools/client/jsonview/components/Headers.js
new file mode 100644
index 0000000000..7477627328
--- /dev/null
+++ b/devtools/client/jsonview/components/Headers.js
@@ -0,0 +1,118 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const {
+ createFactory,
+ Component,
+ } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+
+ const { div, span, table, tbody, tr, td } = dom;
+
+ /**
+ * This template is responsible for rendering basic layout
+ * of the 'Headers' panel. It displays HTTP headers groups such as
+ * received or response headers.
+ */
+ class Headers extends Component {
+ static get propTypes() {
+ return {
+ data: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {};
+ }
+
+ render() {
+ const data = this.props.data;
+
+ return div(
+ { className: "netInfoHeadersTable" },
+ div(
+ { className: "netHeadersGroup" },
+ div(
+ { className: "netInfoHeadersGroup" },
+ JSONView.Locale["jsonViewer.responseHeaders"]
+ ),
+ table(
+ { cellPadding: 0, cellSpacing: 0 },
+ HeaderListFactory({ headers: data.response })
+ )
+ ),
+ div(
+ { className: "netHeadersGroup" },
+ div(
+ { className: "netInfoHeadersGroup" },
+ JSONView.Locale["jsonViewer.requestHeaders"]
+ ),
+ table(
+ { cellPadding: 0, cellSpacing: 0 },
+ HeaderListFactory({ headers: data.request })
+ )
+ )
+ );
+ }
+ }
+
+ /**
+ * This template renders headers list,
+ * name + value pairs.
+ */
+ class HeaderList extends Component {
+ static get propTypes() {
+ return {
+ headers: PropTypes.arrayOf(
+ PropTypes.shape({
+ name: PropTypes.string,
+ value: PropTypes.string,
+ })
+ ),
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ headers: [],
+ };
+ }
+
+ render() {
+ const headers = this.props.headers;
+
+ headers.sort(function (a, b) {
+ return a.name > b.name ? 1 : -1;
+ });
+
+ const rows = [];
+ headers.forEach(header => {
+ rows.push(
+ tr(
+ { key: header.name },
+ td(
+ { className: "netInfoParamName" },
+ span({ title: header.name }, header.name)
+ ),
+ td({ className: "netInfoParamValue" }, header.value)
+ )
+ );
+ });
+
+ return tbody({}, rows);
+ }
+ }
+
+ const HeaderListFactory = createFactory(HeaderList);
+
+ // Exports from this module
+ exports.Headers = Headers;
+});
diff --git a/devtools/client/jsonview/components/HeadersPanel.js b/devtools/client/jsonview/components/HeadersPanel.js
new file mode 100644
index 0000000000..0e9e17190e
--- /dev/null
+++ b/devtools/client/jsonview/components/HeadersPanel.js
@@ -0,0 +1,56 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+
+ const { createFactories } = require("devtools/client/shared/react-utils");
+
+ const { Headers } = createFactories(
+ require("devtools/client/jsonview/components/Headers")
+ );
+ const { HeadersToolbar } = createFactories(
+ require("devtools/client/jsonview/components/HeadersToolbar")
+ );
+
+ const { div } = dom;
+
+ /**
+ * This template represents the 'Headers' panel
+ * s responsible for rendering its content.
+ */
+ class HeadersPanel extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object,
+ data: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ data: {},
+ };
+ }
+
+ render() {
+ const data = this.props.data;
+
+ return div(
+ { className: "headersPanelBox tab-panel-inner" },
+ HeadersToolbar({ actions: this.props.actions }),
+ div({ className: "panelContent" }, Headers({ data }))
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.HeadersPanel = HeadersPanel;
+});
diff --git a/devtools/client/jsonview/components/HeadersToolbar.js b/devtools/client/jsonview/components/HeadersToolbar.js
new file mode 100644
index 0000000000..f9122c3a31
--- /dev/null
+++ b/devtools/client/jsonview/components/HeadersToolbar.js
@@ -0,0 +1,51 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+
+ const { Toolbar, ToolbarButton } = createFactories(
+ require("devtools/client/jsonview/components/reps/Toolbar")
+ );
+
+ /**
+ * This template is responsible for rendering a toolbar
+ * within the 'Headers' panel.
+ */
+ class HeadersToolbar extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onCopy = this.onCopy.bind(this);
+ }
+
+ // Commands
+
+ onCopy(event) {
+ this.props.actions.onCopyHeaders();
+ }
+
+ render() {
+ return Toolbar(
+ {},
+ ToolbarButton(
+ { className: "btn copy", onClick: this.onCopy },
+ JSONView.Locale["jsonViewer.Copy"]
+ )
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.HeadersToolbar = HeadersToolbar;
+});
diff --git a/devtools/client/jsonview/components/JsonPanel.js b/devtools/client/jsonview/components/JsonPanel.js
new file mode 100644
index 0000000000..f569aad4c6
--- /dev/null
+++ b/devtools/client/jsonview/components/JsonPanel.js
@@ -0,0 +1,163 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const {
+ createFactory,
+ Component,
+ } = require("devtools/client/shared/vendor/react");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+
+ const TreeView = createFactory(
+ require("devtools/client/shared/components/tree/TreeView")
+ );
+ const { JsonToolbar } = createFactories(
+ require("devtools/client/jsonview/components/JsonToolbar")
+ );
+
+ const {
+ MODE,
+ } = require("devtools/client/shared/components/reps/reps/constants");
+ const { Rep } = require("devtools/client/shared/components/reps/reps/rep");
+
+ const { div } = dom;
+
+ function isObject(value) {
+ return Object(value) === value;
+ }
+
+ /**
+ * This template represents the 'JSON' panel. The panel is
+ * responsible for rendering an expandable tree that allows simple
+ * inspection of JSON structure.
+ */
+ class JsonPanel extends Component {
+ static get propTypes() {
+ return {
+ data: PropTypes.oneOfType([
+ PropTypes.string,
+ PropTypes.array,
+ PropTypes.object,
+ PropTypes.bool,
+ PropTypes.number,
+ ]),
+ dataSize: PropTypes.number,
+ expandedNodes: PropTypes.instanceOf(Set),
+ searchFilter: PropTypes.string,
+ actions: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {};
+ this.onKeyPress = this.onKeyPress.bind(this);
+ this.onFilter = this.onFilter.bind(this);
+ this.renderValue = this.renderValue.bind(this);
+ this.renderTree = this.renderTree.bind(this);
+ }
+
+ componentDidMount() {
+ document.addEventListener("keypress", this.onKeyPress, true);
+ document.getElementById("json-scrolling-panel").focus();
+ }
+
+ componentWillUnmount() {
+ document.removeEventListener("keypress", this.onKeyPress, true);
+ }
+
+ onKeyPress(e) {
+ // XXX shortcut for focusing the Filter field (see Bug 1178771).
+ }
+
+ onFilter(object) {
+ if (!this.props.searchFilter) {
+ return true;
+ }
+
+ const json = object.name + JSON.stringify(object.value);
+ return json.toLowerCase().includes(this.props.searchFilter.toLowerCase());
+ }
+
+ renderValue(props) {
+ const member = props.member;
+
+ // Hide object summary when non-empty object is expanded (bug 1244912).
+ if (isObject(member.value) && member.hasChildren && member.open) {
+ return null;
+ }
+
+ // Render the value (summary) using Reps library.
+ return Rep(
+ Object.assign({}, props, {
+ cropLimit: 50,
+ noGrip: true,
+ isInContentPage: true,
+ })
+ );
+ }
+
+ renderTree() {
+ // Append custom column for displaying values. This column
+ // Take all available horizontal space.
+ const columns = [
+ {
+ id: "value",
+ width: "100%",
+ },
+ ];
+
+ // Render tree component.
+ return TreeView({
+ object: this.props.data,
+ mode: MODE.TINY,
+ onFilter: this.onFilter,
+ columns,
+ renderValue: this.renderValue,
+ expandedNodes: this.props.expandedNodes,
+ });
+ }
+
+ render() {
+ let content;
+ const data = this.props.data;
+
+ if (!isObject(data)) {
+ content = div(
+ { className: "jsonPrimitiveValue" },
+ Rep({
+ object: data,
+ })
+ );
+ } else if (data instanceof Error) {
+ content = div({ className: "jsonParseError" }, data + "");
+ } else {
+ content = this.renderTree();
+ }
+
+ return div(
+ { className: "jsonPanelBox tab-panel-inner" },
+ JsonToolbar({
+ actions: this.props.actions,
+ dataSize: this.props.dataSize,
+ }),
+ div(
+ {
+ className: "panelContent",
+ id: "json-scrolling-panel",
+ tabIndex: 0,
+ },
+ content
+ )
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.JsonPanel = JsonPanel;
+});
diff --git a/devtools/client/jsonview/components/JsonToolbar.js b/devtools/client/jsonview/components/JsonToolbar.js
new file mode 100644
index 0000000000..34e6ed285b
--- /dev/null
+++ b/devtools/client/jsonview/components/JsonToolbar.js
@@ -0,0 +1,92 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+
+ const { createFactories } = require("devtools/client/shared/react-utils");
+ const { div } = require("devtools/client/shared/vendor/react-dom-factories");
+
+ const { SearchBox } = createFactories(
+ require("devtools/client/jsonview/components/SearchBox")
+ );
+ const { Toolbar, ToolbarButton } = createFactories(
+ require("devtools/client/jsonview/components/reps/Toolbar")
+ );
+
+ /* 100kB file */
+ const EXPAND_THRESHOLD = 100 * 1024;
+
+ /**
+ * This template represents a toolbar within the 'JSON' panel.
+ */
+ class JsonToolbar extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object,
+ dataSize: PropTypes.number,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onSave = this.onSave.bind(this);
+ this.onCopy = this.onCopy.bind(this);
+ this.onCollapse = this.onCollapse.bind(this);
+ this.onExpand = this.onExpand.bind(this);
+ }
+
+ // Commands
+
+ onSave(event) {
+ this.props.actions.onSaveJson();
+ }
+
+ onCopy(event) {
+ this.props.actions.onCopyJson();
+ }
+
+ onCollapse(event) {
+ this.props.actions.onCollapse();
+ }
+
+ onExpand(event) {
+ this.props.actions.onExpand();
+ }
+
+ render() {
+ return Toolbar(
+ {},
+ ToolbarButton(
+ { className: "btn save", onClick: this.onSave },
+ JSONView.Locale["jsonViewer.Save"]
+ ),
+ ToolbarButton(
+ { className: "btn copy", onClick: this.onCopy },
+ JSONView.Locale["jsonViewer.Copy"]
+ ),
+ ToolbarButton(
+ { className: "btn collapse", onClick: this.onCollapse },
+ JSONView.Locale["jsonViewer.CollapseAll"]
+ ),
+ ToolbarButton(
+ { className: "btn expand", onClick: this.onExpand },
+ this.props.dataSize > EXPAND_THRESHOLD
+ ? JSONView.Locale["jsonViewer.ExpandAllSlow"]
+ : JSONView.Locale["jsonViewer.ExpandAll"]
+ ),
+ div({ className: "devtools-separator" }),
+ SearchBox({
+ actions: this.props.actions,
+ })
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.JsonToolbar = JsonToolbar;
+});
diff --git a/devtools/client/jsonview/components/LiveText.js b/devtools/client/jsonview/components/LiveText.js
new file mode 100644
index 0000000000..d90c099340
--- /dev/null
+++ b/devtools/client/jsonview/components/LiveText.js
@@ -0,0 +1,43 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const { findDOMNode } = require("devtools/client/shared/vendor/react-dom");
+ const { pre } = require("devtools/client/shared/vendor/react-dom-factories");
+
+ /**
+ * This object represents a live DOM text node in a <pre>.
+ */
+ class LiveText extends Component {
+ static get propTypes() {
+ return {
+ data: PropTypes.instanceOf(Text),
+ };
+ }
+
+ componentDidMount() {
+ this.componentDidUpdate();
+ }
+
+ componentDidUpdate() {
+ const el = findDOMNode(this);
+ if (el.firstChild === this.props.data) {
+ return;
+ }
+ el.textContent = "";
+ el.append(this.props.data);
+ }
+
+ render() {
+ return pre({ className: "data" });
+ }
+ }
+
+ // Exports from this module
+ exports.LiveText = LiveText;
+});
diff --git a/devtools/client/jsonview/components/MainTabbedArea.js b/devtools/client/jsonview/components/MainTabbedArea.js
new file mode 100644
index 0000000000..f340cbd89e
--- /dev/null
+++ b/devtools/client/jsonview/components/MainTabbedArea.js
@@ -0,0 +1,120 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+ const { JsonPanel } = createFactories(
+ require("devtools/client/jsonview/components/JsonPanel")
+ );
+ const { TextPanel } = createFactories(
+ require("devtools/client/jsonview/components/TextPanel")
+ );
+ const { HeadersPanel } = createFactories(
+ require("devtools/client/jsonview/components/HeadersPanel")
+ );
+ const { Tabs, TabPanel } = createFactories(
+ require("devtools/client/shared/components/tabs/Tabs")
+ );
+
+ /**
+ * This object represents the root application template
+ * responsible for rendering the basic tab layout.
+ */
+ class MainTabbedArea extends Component {
+ static get propTypes() {
+ return {
+ jsonText: PropTypes.instanceOf(Text),
+ activeTab: PropTypes.number,
+ actions: PropTypes.object,
+ headers: PropTypes.object,
+ searchFilter: PropTypes.string,
+ json: PropTypes.oneOfType([
+ PropTypes.string,
+ PropTypes.object,
+ PropTypes.array,
+ PropTypes.bool,
+ PropTypes.number,
+ ]),
+ expandedNodes: PropTypes.instanceOf(Set),
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ json: props.json,
+ expandedNodes: props.expandedNodes,
+ jsonText: props.jsonText,
+ activeTab: props.activeTab,
+ };
+
+ this.onTabChanged = this.onTabChanged.bind(this);
+ }
+
+ onTabChanged(index) {
+ this.setState({ activeTab: index });
+
+ // Send notification event to the window. This is useful for tests.
+ window.dispatchEvent(new CustomEvent("TabChanged"));
+ }
+
+ render() {
+ return Tabs(
+ {
+ activeTab: this.state.activeTab,
+ onAfterChange: this.onTabChanged,
+ tall: true,
+ },
+ TabPanel(
+ {
+ id: "json",
+ className: "json",
+ title: JSONView.Locale["jsonViewer.tab.JSON"],
+ },
+ JsonPanel({
+ data: this.state.json,
+ expandedNodes: this.state.expandedNodes,
+ actions: this.props.actions,
+ searchFilter: this.state.searchFilter,
+ dataSize: this.state.jsonText.length,
+ })
+ ),
+ TabPanel(
+ {
+ id: "rawdata",
+ className: "rawdata",
+ title: JSONView.Locale["jsonViewer.tab.RawData"],
+ },
+ TextPanel({
+ isValidJson:
+ !(this.state.json instanceof Error) &&
+ document.readyState != "loading",
+ data: this.state.jsonText,
+ actions: this.props.actions,
+ })
+ ),
+ TabPanel(
+ {
+ id: "headers",
+ className: "headers",
+ title: JSONView.Locale["jsonViewer.tab.Headers"],
+ },
+ HeadersPanel({
+ data: this.props.headers,
+ actions: this.props.actions,
+ searchFilter: this.props.searchFilter,
+ })
+ )
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.MainTabbedArea = MainTabbedArea;
+});
diff --git a/devtools/client/jsonview/components/SearchBox.js b/devtools/client/jsonview/components/SearchBox.js
new file mode 100644
index 0000000000..cb736db85b
--- /dev/null
+++ b/devtools/client/jsonview/components/SearchBox.js
@@ -0,0 +1,102 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+
+ const { input, div, button } = dom;
+
+ // For smooth incremental searching (in case the user is typing quickly).
+ const searchDelay = 250;
+
+ /**
+ * This object represents a search box located at the
+ * top right corner of the application.
+ */
+ class SearchBox extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object,
+ value: PropTypes.toString,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onSearch = this.onSearch.bind(this);
+ this.doSearch = this.doSearch.bind(this);
+ this.onClearButtonClick = this.onClearButtonClick.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+
+ this.state = {
+ value: props.value || "",
+ };
+ }
+
+ onSearch(event) {
+ this.setState({
+ value: event.target.value,
+ });
+ const searchBox = event.target;
+ const win = searchBox.ownerDocument.defaultView;
+
+ if (this.searchTimeout) {
+ win.clearTimeout(this.searchTimeout);
+ }
+
+ const callback = this.doSearch.bind(this, searchBox);
+ this.searchTimeout = win.setTimeout(callback, searchDelay);
+ }
+
+ doSearch(searchBox) {
+ this.props.actions.onSearch(searchBox.value);
+ }
+
+ onClearButtonClick() {
+ this.setState({ value: "" });
+ this.props.actions.onSearch("");
+ if (this._searchBoxRef) {
+ this._searchBoxRef.focus();
+ }
+ }
+
+ onKeyDown(e) {
+ switch (e.key) {
+ case "Escape":
+ e.preventDefault();
+ this.onClearButtonClick();
+ break;
+ }
+ }
+
+ render() {
+ const { value } = this.state;
+ return div(
+ { className: "devtools-searchbox" },
+ input({
+ className: "searchBox devtools-filterinput",
+ placeholder: JSONView.Locale["jsonViewer.filterJSON"],
+ onChange: this.onSearch,
+ onKeyDown: this.onKeyDown,
+ value,
+ ref: c => {
+ this._searchBoxRef = c;
+ },
+ }),
+ button({
+ className: "devtools-searchinput-clear",
+ hidden: !value,
+ onClick: this.onClearButtonClick,
+ })
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.SearchBox = SearchBox;
+});
diff --git a/devtools/client/jsonview/components/TextPanel.js b/devtools/client/jsonview/components/TextPanel.js
new file mode 100644
index 0000000000..a830d9d01b
--- /dev/null
+++ b/devtools/client/jsonview/components/TextPanel.js
@@ -0,0 +1,52 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+ const { TextToolbar } = createFactories(
+ require("devtools/client/jsonview/components/TextToolbar")
+ );
+ const { LiveText } = createFactories(
+ require("devtools/client/jsonview/components/LiveText")
+ );
+ const { div } = dom;
+
+ /**
+ * This template represents the 'Raw Data' panel displaying
+ * JSON as a text received from the server.
+ */
+ class TextPanel extends Component {
+ static get propTypes() {
+ return {
+ isValidJson: PropTypes.bool,
+ actions: PropTypes.object,
+ data: PropTypes.instanceOf(Text),
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {};
+ }
+
+ render() {
+ return div(
+ { className: "textPanelBox tab-panel-inner" },
+ TextToolbar({
+ actions: this.props.actions,
+ isValidJson: this.props.isValidJson,
+ }),
+ div({ className: "panelContent" }, LiveText({ data: this.props.data }))
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.TextPanel = TextPanel;
+});
diff --git a/devtools/client/jsonview/components/TextToolbar.js b/devtools/client/jsonview/components/TextToolbar.js
new file mode 100644
index 0000000000..0ab16ef192
--- /dev/null
+++ b/devtools/client/jsonview/components/TextToolbar.js
@@ -0,0 +1,80 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+ const { Toolbar, ToolbarButton } = createFactories(
+ require("devtools/client/jsonview/components/reps/Toolbar")
+ );
+
+ /**
+ * This object represents a toolbar displayed within the
+ * 'Raw Data' panel.
+ */
+ class TextToolbar extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object,
+ isValidJson: PropTypes.bool,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onPrettify = this.onPrettify.bind(this);
+ this.onSave = this.onSave.bind(this);
+ this.onCopy = this.onCopy.bind(this);
+ }
+
+ // Commands
+
+ onPrettify(event) {
+ this.props.actions.onPrettify();
+ }
+
+ onSave(event) {
+ this.props.actions.onSaveJson();
+ }
+
+ onCopy(event) {
+ this.props.actions.onCopyJson();
+ }
+
+ render() {
+ return Toolbar(
+ {},
+ ToolbarButton(
+ {
+ className: "btn save",
+ onClick: this.onSave,
+ },
+ JSONView.Locale["jsonViewer.Save"]
+ ),
+ ToolbarButton(
+ {
+ className: "btn copy",
+ onClick: this.onCopy,
+ },
+ JSONView.Locale["jsonViewer.Copy"]
+ ),
+ this.props.isValidJson
+ ? ToolbarButton(
+ {
+ className: "btn prettyprint",
+ onClick: this.onPrettify,
+ },
+ JSONView.Locale["jsonViewer.PrettyPrint"]
+ )
+ : null
+ );
+ }
+ }
+
+ // Exports from this module
+ exports.TextToolbar = TextToolbar;
+});
diff --git a/devtools/client/jsonview/components/moz.build b/devtools/client/jsonview/components/moz.build
new file mode 100644
index 0000000000..8cb9dc8e87
--- /dev/null
+++ b/devtools/client/jsonview/components/moz.build
@@ -0,0 +1,20 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += ["reps"]
+
+DevToolsModules(
+ "Headers.js",
+ "HeadersPanel.js",
+ "HeadersToolbar.js",
+ "JsonPanel.js",
+ "JsonToolbar.js",
+ "LiveText.js",
+ "MainTabbedArea.js",
+ "SearchBox.js",
+ "TextPanel.js",
+ "TextToolbar.js",
+)
diff --git a/devtools/client/jsonview/components/reps/Toolbar.js b/devtools/client/jsonview/components/reps/Toolbar.js
new file mode 100644
index 0000000000..458acf236f
--- /dev/null
+++ b/devtools/client/jsonview/components/reps/Toolbar.js
@@ -0,0 +1,48 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { Component } = require("devtools/client/shared/vendor/react");
+ const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
+ const dom = require("devtools/client/shared/vendor/react-dom-factories");
+
+ /**
+ * Renders a simple toolbar.
+ */
+ class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ children: PropTypes.oneOfType([PropTypes.array, PropTypes.element]),
+ };
+ }
+
+ render() {
+ return dom.div({ className: "toolbar" }, this.props.children);
+ }
+ }
+
+ /**
+ * Renders a simple toolbar button.
+ */
+ class ToolbarButton extends Component {
+ static get propTypes() {
+ return {
+ active: PropTypes.bool,
+ disabled: PropTypes.bool,
+ children: PropTypes.string,
+ };
+ }
+
+ render() {
+ const props = Object.assign({ className: "btn" }, this.props);
+ return dom.button(props, this.props.children);
+ }
+ }
+
+ // Exports from this module
+ exports.Toolbar = Toolbar;
+ exports.ToolbarButton = ToolbarButton;
+});
diff --git a/devtools/client/jsonview/components/reps/moz.build b/devtools/client/jsonview/components/reps/moz.build
new file mode 100644
index 0000000000..ba39d7767b
--- /dev/null
+++ b/devtools/client/jsonview/components/reps/moz.build
@@ -0,0 +1,9 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "Toolbar.js",
+)
diff --git a/devtools/client/jsonview/converter-child.js b/devtools/client/jsonview/converter-child.js
new file mode 100644
index 0000000000..1e14e8dacb
--- /dev/null
+++ b/devtools/client/jsonview/converter-child.js
@@ -0,0 +1,419 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const {
+ getTheme,
+ addThemeObserver,
+ removeThemeObserver,
+} = require("resource://devtools/client/shared/theme.js");
+
+const BinaryInput = Components.Constructor(
+ "@mozilla.org/binaryinputstream;1",
+ "nsIBinaryInputStream",
+ "setInputStream"
+);
+const BufferStream = Components.Constructor(
+ "@mozilla.org/io/arraybuffer-input-stream;1",
+ "nsIArrayBufferInputStream",
+ "setData"
+);
+
+const kCSP = "default-src 'none' ; script-src resource:; ";
+
+// Localization
+loader.lazyGetter(this, "jsonViewStrings", () => {
+ return Services.strings.createBundle(
+ "chrome://devtools/locale/jsonview.properties"
+ );
+});
+
+/**
+ * This object detects 'application/vnd.mozilla.json.view' content type
+ * and converts it into a JSON Viewer application that allows simple
+ * JSON inspection.
+ *
+ * Inspired by JSON View: https://github.com/bhollis/jsonview/
+ */
+function Converter() {}
+
+Converter.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIStreamConverter",
+ "nsIStreamListener",
+ "nsIRequestObserver",
+ ]),
+
+ get wrappedJSObject() {
+ return this;
+ },
+
+ /**
+ * This component works as such:
+ * 1. asyncConvertData captures the listener
+ * 2. onStartRequest fires, initializes stuff, modifies the listener
+ * to match our output type
+ * 3. onDataAvailable decodes and inserts data into a text node
+ * 4. onStopRequest flushes data and spits back to the listener
+ * 5. convert does nothing, it's just the synchronous version
+ * of asyncConvertData
+ */
+ convert(fromStream, fromType, toType, ctx) {
+ return fromStream;
+ },
+
+ asyncConvertData(fromType, toType, listener, ctx) {
+ this.listener = listener;
+ },
+ getConvertedType(fromType, channel) {
+ return "text/html";
+ },
+
+ onDataAvailable(request, inputStream, offset, count) {
+ // Decode and insert data.
+ const buffer = new ArrayBuffer(count);
+ new BinaryInput(inputStream).readArrayBuffer(count, buffer);
+ this.decodeAndInsertBuffer(buffer);
+ },
+
+ onStartRequest(request) {
+ // Set the content type to HTML in order to parse the doctype, styles
+ // and scripts. The JSON will be manually inserted as text.
+ request.QueryInterface(Ci.nsIChannel);
+ request.contentType = "text/html";
+
+ const headers = getHttpHeaders(request);
+
+ // Enforce strict CSP:
+ try {
+ request.QueryInterface(Ci.nsIHttpChannel);
+ request.setResponseHeader("Content-Security-Policy", kCSP, false);
+ request.setResponseHeader(
+ "Content-Security-Policy-Report-Only",
+ "",
+ false
+ );
+ } catch (ex) {
+ // If this is not an HTTP channel we can't and won't do anything.
+ }
+
+ // Don't honor the charset parameter and use UTF-8 (see bug 741776).
+ request.contentCharset = "UTF-8";
+ this.decoder = new TextDecoder("UTF-8");
+
+ // Changing the content type breaks saving functionality. Fix it.
+ fixSave(request);
+
+ // Because content might still have a reference to this window,
+ // force setting it to a null principal to avoid it being same-
+ // origin with (other) content.
+ request.loadInfo.resetPrincipalToInheritToNullPrincipal();
+
+ // Start the request.
+ this.listener.onStartRequest(request);
+
+ // Initialize stuff.
+ const win = getWindowForRequest(request);
+ if (!win || !Components.isSuccessCode(request.status)) {
+ return;
+ }
+
+ // We compare actual pointer identities here rather than using .equals(),
+ // because if things went correctly then the document must have exactly
+ // the principal we reset it to above. If not, something went wrong.
+ if (win.document.nodePrincipal != request.loadInfo.principalToInherit) {
+ // Whatever that document is, it's not ours.
+ request.cancel(Cr.NS_BINDING_ABORTED);
+ return;
+ }
+
+ this.data = exportData(win, headers);
+ insertJsonData(win, this.data.json);
+ win.addEventListener("contentMessage", onContentMessage, false, true);
+ keepThemeUpdated(win);
+
+ // Send the initial HTML code.
+ const buffer = new TextEncoder().encode(initialHTML(win.document)).buffer;
+ const stream = new BufferStream(buffer, 0, buffer.byteLength);
+ this.listener.onDataAvailable(request, stream, 0, stream.available());
+ },
+
+ onStopRequest(request, statusCode) {
+ // Flush data if we haven't been canceled.
+ if (Components.isSuccessCode(statusCode)) {
+ this.decodeAndInsertBuffer(new ArrayBuffer(0), true);
+ }
+
+ // Stop the request.
+ this.listener.onStopRequest(request, statusCode);
+ this.listener = null;
+ this.decoder = null;
+ this.data = null;
+ },
+
+ // Decodes an ArrayBuffer into a string and inserts it into the page.
+ decodeAndInsertBuffer(buffer, flush = false) {
+ // Decode the buffer into a string.
+ const data = this.decoder.decode(buffer, { stream: !flush });
+
+ // Using `appendData` instead of `textContent +=` is important to avoid
+ // repainting previous data.
+ this.data.json.appendData(data);
+ },
+};
+
+// Lets "save as" save the original JSON, not the viewer.
+// To save with the proper extension we need the original content type,
+// which has been replaced by application/vnd.mozilla.json.view
+function fixSave(request) {
+ let match;
+ if (request instanceof Ci.nsIHttpChannel) {
+ try {
+ const header = request.getResponseHeader("Content-Type");
+ match = header.match(/^(application\/(?:[^;]+\+)?json)(?:;|$)/);
+ } catch (err) {
+ // Handled below
+ }
+ } else {
+ const uri = request.QueryInterface(Ci.nsIChannel).URI.spec;
+ match = uri.match(/^data:(application\/(?:[^;,]+\+)?json)[;,]/);
+ }
+ let originalType;
+ if (match) {
+ originalType = match[1];
+ } else {
+ originalType = "application/json";
+ }
+ request.QueryInterface(Ci.nsIWritablePropertyBag);
+ request.setProperty("contentType", originalType);
+}
+
+function getHttpHeaders(request) {
+ const headers = {
+ response: [],
+ request: [],
+ };
+ // The request doesn't have to be always nsIHttpChannel
+ // (e.g. in case of data: URLs)
+ if (request instanceof Ci.nsIHttpChannel) {
+ request.visitResponseHeaders({
+ visitHeader(name, value) {
+ headers.response.push({ name, value });
+ },
+ });
+ request.visitRequestHeaders({
+ visitHeader(name, value) {
+ headers.request.push({ name, value });
+ },
+ });
+ }
+ return headers;
+}
+
+let jsonViewStringDict = null;
+function getAllStrings() {
+ if (!jsonViewStringDict) {
+ jsonViewStringDict = {};
+ for (const string of jsonViewStrings.getSimpleEnumeration()) {
+ jsonViewStringDict[string.key] = string.value;
+ }
+ }
+ return jsonViewStringDict;
+}
+
+// The two following methods are duplicated from NetworkHelper.sys.mjs
+// to avoid pulling the whole NetworkHelper as a dependency during
+// initialization.
+
+/**
+ * Gets the nsIDOMWindow that is associated with request.
+ *
+ * @param nsIHttpChannel request
+ * @returns nsIDOMWindow or null
+ */
+function getWindowForRequest(request) {
+ try {
+ return getRequestLoadContext(request).associatedWindow;
+ } catch (ex) {
+ // On some request notificationCallbacks and loadGroup are both null,
+ // so that we can't retrieve any nsILoadContext interface.
+ // Fallback on nsILoadInfo to try to retrieve the request's window.
+ // (this is covered by test_network_get.html and its CSS request)
+ return request.loadInfo.loadingDocument?.defaultView;
+ }
+}
+
+/**
+ * Gets the nsILoadContext that is associated with request.
+ *
+ * @param nsIHttpChannel request
+ * @returns nsILoadContext or null
+ */
+function getRequestLoadContext(request) {
+ try {
+ return request.notificationCallbacks.getInterface(Ci.nsILoadContext);
+ } catch (ex) {
+ // Ignore.
+ }
+
+ try {
+ return request.loadGroup.notificationCallbacks.getInterface(
+ Ci.nsILoadContext
+ );
+ } catch (ex) {
+ // Ignore.
+ }
+
+ return null;
+}
+
+// Exports variables that will be accessed by the non-privileged scripts.
+function exportData(win, headers) {
+ const json = new win.Text();
+ const JSONView = Cu.cloneInto(
+ {
+ headers,
+ json,
+ readyState: "uninitialized",
+ Locale: getAllStrings(),
+ },
+ win,
+ {
+ wrapReflectors: true,
+ }
+ );
+ try {
+ Object.defineProperty(Cu.waiveXrays(win), "JSONView", {
+ value: JSONView,
+ configurable: true,
+ enumerable: true,
+ writable: true,
+ });
+ } catch (error) {
+ console.error(error);
+ }
+ return { json };
+}
+
+// Builds an HTML string that will be used to load stylesheets and scripts.
+function initialHTML(doc) {
+ // Creates an element with the specified type, attributes and children.
+ function element(type, attributes = {}, children = []) {
+ const el = doc.createElement(type);
+ for (const [attr, value] of Object.entries(attributes)) {
+ el.setAttribute(attr, value);
+ }
+ el.append(...children);
+ return el;
+ }
+
+ let os;
+ const platform = Services.appinfo.OS;
+ if (platform.startsWith("WINNT")) {
+ os = "win";
+ } else if (platform.startsWith("Darwin")) {
+ os = "mac";
+ } else {
+ os = "linux";
+ }
+
+ const baseURI = "resource://devtools-client-jsonview/";
+
+ return (
+ "<!DOCTYPE html>\n" +
+ element(
+ "html",
+ {
+ platform: os,
+ class: "theme-" + getTheme(),
+ dir: Services.locale.isAppLocaleRTL ? "rtl" : "ltr",
+ },
+ [
+ element("head", {}, [
+ element("meta", {
+ "http-equiv": "Content-Security-Policy",
+ content: kCSP,
+ }),
+ element("link", {
+ rel: "stylesheet",
+ type: "text/css",
+ href: "chrome://devtools-jsonview-styles/content/main.css",
+ }),
+ ]),
+ element("body", {}, [
+ element("div", { id: "content" }, [element("div", { id: "json" })]),
+ element("script", {
+ src: baseURI + "lib/require.js",
+ "data-main": baseURI + "viewer-config.js",
+ }),
+ ]),
+ ]
+ ).outerHTML
+ );
+}
+
+// We insert the received data into a text node, which should be appended into
+// the #json element so that the JSON is still displayed even if JS is disabled.
+// However, the HTML parser is not synchronous, so this function uses a mutation
+// observer to detect the creation of the element. Then the text node is appended.
+function insertJsonData(win, json) {
+ new win.MutationObserver(function (mutations, observer) {
+ for (const { target, addedNodes } of mutations) {
+ if (target.nodeType == 1 && target.id == "content") {
+ for (const node of addedNodes) {
+ if (node.nodeType == 1 && node.id == "json") {
+ observer.disconnect();
+ node.append(json);
+ return;
+ }
+ }
+ }
+ }
+ }).observe(win.document, {
+ childList: true,
+ subtree: true,
+ });
+}
+
+function keepThemeUpdated(win) {
+ const listener = function () {
+ win.document.documentElement.className = "theme-" + getTheme();
+ };
+ addThemeObserver(listener);
+ win.addEventListener(
+ "unload",
+ function (event) {
+ removeThemeObserver(listener);
+ win = null;
+ },
+ { once: true }
+ );
+}
+
+// Chrome <-> Content communication
+function onContentMessage(e) {
+ // Do not handle events from different documents.
+ const win = this;
+ if (win != e.target) {
+ return;
+ }
+
+ const value = e.detail.value;
+ switch (e.detail.type) {
+ case "save":
+ win.docShell.messageManager.sendAsyncMessage(
+ "devtools:jsonview:save",
+ value
+ );
+ }
+}
+
+function createInstance() {
+ return new Converter();
+}
+
+exports.JsonViewService = {
+ createInstance,
+};
diff --git a/devtools/client/jsonview/css/general.css b/devtools/client/jsonview/css/general.css
new file mode 100644
index 0000000000..1fb15fdfc3
--- /dev/null
+++ b/devtools/client/jsonview/css/general.css
@@ -0,0 +1,48 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* General */
+
+html, body, #content {
+ height: 100%;
+}
+
+body {
+ color: var(--theme-body-color);
+ background-color: var(--theme-body-background);
+ padding: 0;
+ margin: 0;
+}
+
+*:focus {
+ outline: none !important;
+}
+
+pre {
+ background-color: white;
+ border: none;
+ font-family: var(--monospace-font-family);
+}
+
+#content {
+ display: flow-root;
+}
+
+#json {
+ margin: 8px;
+ white-space: pre-wrap;
+}
+
+/******************************************************************************/
+/* Dark Theme */
+
+body.theme-dark {
+ color: var(--theme-body-color);
+ background-color: var(--theme-body-background);
+}
+
+.theme-dark pre {
+ background-color: var(--theme-body-background);
+}
diff --git a/devtools/client/jsonview/css/headers-panel.css b/devtools/client/jsonview/css/headers-panel.css
new file mode 100644
index 0000000000..b37340b51a
--- /dev/null
+++ b/devtools/client/jsonview/css/headers-panel.css
@@ -0,0 +1,66 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* Headers Panel */
+
+.headersPanelBox {
+ height: 100%;
+}
+
+.headersPanelBox .netInfoHeadersTable {
+ overflow: auto;
+ height: 100%;
+}
+
+.headersPanelBox .netHeadersGroup {
+ padding: 10px;
+}
+
+.headersPanelBox td {
+ vertical-align: bottom;
+}
+
+.headersPanelBox .netInfoHeadersGroup {
+ color: var(--theme-toolbar-color);
+ margin-bottom: 10px;
+ border-bottom: 1px solid var(--theme-splitter-color);
+ padding-top: 8px;
+ padding-bottom: 4px;
+ font-weight: bold;
+ user-select: none;
+}
+
+.headersPanelBox .netInfoParamValue {
+ word-wrap: break-word;
+}
+
+.headersPanelBox .netInfoParamName {
+ padding: 2px 10px 0 0;
+ font-weight: bold;
+ vertical-align: top;
+ text-align: right;
+ white-space: nowrap;
+}
+
+/******************************************************************************/
+/* Theme colors have been generated/copied from Network Panel's header view */
+
+/* Light Theme */
+.theme-light .netInfoParamName {
+ color: var(--theme-highlight-red);
+}
+
+.theme-light .netInfoParamValue {
+ color: var(--theme-highlight-purple);
+}
+
+/* Dark Theme */
+.theme-dark .netInfoParamName {
+ color: var(--theme-highlight-purple);
+}
+
+.theme-dark .netInfoParamValue {
+ color: var(--theme-highlight-gray);
+}
diff --git a/devtools/client/jsonview/css/json-panel.css b/devtools/client/jsonview/css/json-panel.css
new file mode 100644
index 0000000000..98c228e87e
--- /dev/null
+++ b/devtools/client/jsonview/css/json-panel.css
@@ -0,0 +1,18 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* JSON Panel */
+
+.jsonPrimitiveValue,
+.jsonParseError {
+ font-size: 12px;
+ font-family: Lucida Grande, Tahoma, sans-serif;
+ line-height: 15px;
+ padding: 10px;
+}
+
+.jsonParseError {
+ color: var(--theme-text-color-error);
+}
diff --git a/devtools/client/jsonview/css/main.css b/devtools/client/jsonview/css/main.css
new file mode 100644
index 0000000000..996b6b7a4d
--- /dev/null
+++ b/devtools/client/jsonview/css/main.css
@@ -0,0 +1,44 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+@import "chrome://devtools/skin/variables.css";
+@import "chrome://devtools/skin/common.css";
+@import "chrome://devtools/skin/toolbars.css";
+
+@import "chrome://devtools/content/shared/components/tree/TreeView.css";
+@import "chrome://devtools/content/shared/components/tabs/Tabs.css";
+
+@import "general.css";
+@import "search-box.css";
+@import "toolbar.css";
+@import "json-panel.css";
+@import "text-panel.css";
+@import "headers-panel.css";
+
+/******************************************************************************/
+/* Panel Content */
+
+.tab-panel-inner {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.panelContent {
+ direction: ltr;
+ overflow-y: auto;
+ width: 100%;
+ flex: 1;
+}
+
+/* The tree takes the entire horizontal space within the panel content. */
+.panelContent .treeTable {
+ width: 100%;
+ font-family: var(--monospace-font-family);
+}
+
+/* Make sure there is a little space between label and value columns. */
+.panelContent .treeTable .treeLabelCell {
+ padding-right: 17px;
+}
diff --git a/devtools/client/jsonview/css/moz.build b/devtools/client/jsonview/css/moz.build
new file mode 100644
index 0000000000..53ebea91b0
--- /dev/null
+++ b/devtools/client/jsonview/css/moz.build
@@ -0,0 +1,15 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "general.css",
+ "headers-panel.css",
+ "json-panel.css",
+ "main.css",
+ "search-box.css",
+ "text-panel.css",
+ "toolbar.css",
+)
diff --git a/devtools/client/jsonview/css/search-box.css b/devtools/client/jsonview/css/search-box.css
new file mode 100644
index 0000000000..25828c6b76
--- /dev/null
+++ b/devtools/client/jsonview/css/search-box.css
@@ -0,0 +1,20 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* Search Box */
+
+.devtools-searchbox {
+ background-color: var(--theme-body-background);
+}
+
+.devtools-filterinput {
+ margin-inline-start: auto; /* Align to the right */
+}
+
+/* JSONView doesn't load dark-theme.css */
+.theme-dark .devtools-filterinput {
+ background-color: rgba(24, 29, 32, 1);
+ color: rgba(184, 200, 217, 1);
+}
diff --git a/devtools/client/jsonview/css/text-panel.css b/devtools/client/jsonview/css/text-panel.css
new file mode 100644
index 0000000000..b656918898
--- /dev/null
+++ b/devtools/client/jsonview/css/text-panel.css
@@ -0,0 +1,18 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* Text Panel */
+
+.textPanelBox {
+ height: 100%;
+}
+
+.textPanelBox pre {
+ margin: 8px;
+ white-space: pre-wrap;
+ overflow-wrap: break-word;
+ font-family: var(--monospace-font-family);
+ color: var(--theme-text-color-strong);
+}
diff --git a/devtools/client/jsonview/css/toolbar.css b/devtools/client/jsonview/css/toolbar.css
new file mode 100644
index 0000000000..58349d887c
--- /dev/null
+++ b/devtools/client/jsonview/css/toolbar.css
@@ -0,0 +1,39 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/******************************************************************************/
+/* Toolbar */
+
+.toolbar {
+ display: flex;
+ height: 22px;
+ padding: 1px;
+ padding-inline-start: 2px;
+ background: var(--theme-toolbar-background);
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+.toolbar .btn {
+ margin-inline-start: 5px;
+ color: var(--theme-body-color);
+ background: var(--toolbarbutton-background);
+ border: none;
+ text-decoration: none;
+ display: inline-block;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ cursor: pointer;
+ user-select: none;
+ padding: 0 3px;
+ border-radius: 2px;
+}
+
+.toolbar .btn:hover {
+ background: var(--toolbarbutton-hover-background);
+}
+
+.toolbar .btn:not([disabled]):hover:active {
+ background-color: var(--theme-selection-background-hover);
+}
diff --git a/devtools/client/jsonview/json-viewer.js b/devtools/client/jsonview/json-viewer.js
new file mode 100644
index 0000000000..139ed31f61
--- /dev/null
+++ b/devtools/client/jsonview/json-viewer.js
@@ -0,0 +1,203 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+define(function (require, exports, module) {
+ const { render } = require("devtools/client/shared/vendor/react-dom");
+ const { createFactories } = require("devtools/client/shared/react-utils");
+ const { MainTabbedArea } = createFactories(
+ require("devtools/client/jsonview/components/MainTabbedArea")
+ );
+ const TreeViewClass = require("devtools/client/shared/components/tree/TreeView");
+
+ const AUTO_EXPAND_MAX_SIZE = 100 * 1024;
+ const AUTO_EXPAND_MAX_LEVEL = 7;
+
+ let prettyURL;
+ let theApp;
+
+ // Application state object.
+ const input = {
+ jsonText: JSONView.json,
+ jsonPretty: null,
+ headers: JSONView.headers,
+ activeTab: 0,
+ prettified: false,
+ expandedNodes: new Set(),
+ };
+
+ /**
+ * Application actions/commands. This list implements all commands
+ * available for the JSON viewer.
+ */
+ input.actions = {
+ onCopyJson() {
+ const text = input.prettified ? input.jsonPretty : input.jsonText;
+ copyString(text.textContent);
+ },
+
+ onSaveJson() {
+ if (input.prettified && !prettyURL) {
+ prettyURL = URL.createObjectURL(
+ new window.Blob([input.jsonPretty.textContent])
+ );
+ }
+ dispatchEvent("save", input.prettified ? prettyURL : null);
+ },
+
+ onCopyHeaders() {
+ let value = "";
+ const isWinNT =
+ document.documentElement.getAttribute("platform") === "win";
+ const eol = isWinNT ? "\r\n" : "\n";
+
+ const responseHeaders = input.headers.response;
+ for (let i = 0; i < responseHeaders.length; i++) {
+ const header = responseHeaders[i];
+ value += header.name + ": " + header.value + eol;
+ }
+
+ value += eol;
+
+ const requestHeaders = input.headers.request;
+ for (let i = 0; i < requestHeaders.length; i++) {
+ const header = requestHeaders[i];
+ value += header.name + ": " + header.value + eol;
+ }
+
+ copyString(value);
+ },
+
+ onSearch(value) {
+ theApp.setState({ searchFilter: value });
+ },
+
+ onPrettify(data) {
+ if (input.json instanceof Error) {
+ // Cannot prettify invalid JSON
+ return;
+ }
+ if (input.prettified) {
+ theApp.setState({ jsonText: input.jsonText });
+ } else {
+ if (!input.jsonPretty) {
+ input.jsonPretty = new Text(JSON.stringify(input.json, null, " "));
+ }
+ theApp.setState({ jsonText: input.jsonPretty });
+ }
+
+ input.prettified = !input.prettified;
+ },
+
+ onCollapse(data) {
+ input.expandedNodes.clear();
+ theApp.forceUpdate();
+ },
+
+ onExpand(data) {
+ input.expandedNodes = TreeViewClass.getExpandedNodes(input.json);
+ theApp.setState({ expandedNodes: input.expandedNodes });
+ },
+ };
+
+ /**
+ * Helper for copying a string to the clipboard.
+ *
+ * @param {String} string The text to be copied.
+ */
+ function copyString(string) {
+ document.addEventListener(
+ "copy",
+ event => {
+ event.clipboardData.setData("text/plain", string);
+ event.preventDefault();
+ },
+ { once: true }
+ );
+
+ document.execCommand("copy", false, null);
+ }
+
+ /**
+ * Helper for dispatching an event. It's handled in chrome scope.
+ *
+ * @param {String} type Event detail type
+ * @param {Object} value Event detail value
+ */
+ function dispatchEvent(type, value) {
+ const data = {
+ detail: {
+ type,
+ value,
+ },
+ };
+
+ const contentMessageEvent = new CustomEvent("contentMessage", data);
+ window.dispatchEvent(contentMessageEvent);
+ }
+
+ /**
+ * Render the main application component. It's the main tab bar displayed
+ * at the top of the window. This component also represents ReacJS root.
+ */
+ const content = document.getElementById("content");
+ const promise = (async function parseJSON() {
+ if (document.readyState == "loading") {
+ // If the JSON has not been loaded yet, render the Raw Data tab first.
+ input.json = {};
+ input.activeTab = 1;
+ return new Promise(resolve => {
+ document.addEventListener("DOMContentLoaded", resolve, { once: true });
+ })
+ .then(parseJSON)
+ .then(async () => {
+ // Now update the state and switch to the JSON tab.
+ await appIsReady;
+ theApp.setState({
+ activeTab: 0,
+ json: input.json,
+ expandedNodes: input.expandedNodes,
+ });
+ });
+ }
+
+ // If the JSON has been loaded, parse it immediately before loading the app.
+ const jsonString = input.jsonText.textContent;
+ try {
+ input.json = JSON.parse(jsonString);
+ } catch (err) {
+ input.json = err;
+ }
+
+ // Expand the document by default if its size isn't bigger than 100KB.
+ if (
+ !(input.json instanceof Error) &&
+ jsonString.length <= AUTO_EXPAND_MAX_SIZE
+ ) {
+ input.expandedNodes = TreeViewClass.getExpandedNodes(input.json, {
+ maxLevel: AUTO_EXPAND_MAX_LEVEL,
+ });
+ }
+ return undefined;
+ })();
+
+ const appIsReady = new Promise(resolve => {
+ render(MainTabbedArea(input), content, function () {
+ theApp = this;
+ resolve();
+
+ // Send readyState change notification event to the window. Can be useful for
+ // tests as well as extensions.
+ JSONView.readyState = "interactive";
+ window.dispatchEvent(new CustomEvent("AppReadyStateChange"));
+
+ promise.then(() => {
+ // Another readyState change notification event.
+ JSONView.readyState = "complete";
+ window.dispatchEvent(new CustomEvent("AppReadyStateChange"));
+ });
+ });
+ });
+});
diff --git a/devtools/client/jsonview/lib/moz.build b/devtools/client/jsonview/lib/moz.build
new file mode 100644
index 0000000000..461ef2e445
--- /dev/null
+++ b/devtools/client/jsonview/lib/moz.build
@@ -0,0 +1,7 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules("require.js")
diff --git a/devtools/client/jsonview/lib/require.js b/devtools/client/jsonview/lib/require.js
new file mode 100644
index 0000000000..eefa4e55c8
--- /dev/null
+++ b/devtools/client/jsonview/lib/require.js
@@ -0,0 +1,2080 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+var requirejs, require, define;
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.15',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value === 'object' && value &&
+ !isArray(value) && !isFunction(value) &&
+ !(value instanceof RegExp)) {
+
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ function defaultOnError(err) {
+ throw err;
+ }
+
+ //Allow getting a global that is expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite an existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ bundles: {},
+ pkgs: {},
+ shim: {},
+ config: {}
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ bundlesMap = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part;
+ for (i = 0; i < ary.length; i++) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ // If at the start, or previous value is still ..,
+ // keep them so that when converted to a path it may
+ // still work when converted to a path, even though
+ // as an ID it is less than ideal. In larger point
+ // releases, may be better to just kick out an error.
+ if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
+ continue;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
+ foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
+ baseParts = (baseName && baseName.split('/')),
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name) {
+ name = name.split('/');
+ lastIndex = name.length - 1;
+
+ // If wanting node ID compatibility, strip .js from end
+ // of IDs. Have to do this here, and not in nameToUrl
+ // because node allows either .js or non .js to map
+ // to same file.
+ if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
+ name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
+ }
+
+ // Starts with a '.' so need the baseName
+ if (name[0].charAt(0) === '.' && baseParts) {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ name = normalizedBaseParts.concat(name);
+ }
+
+ trimDots(name);
+ name = name.join('/');
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/');
+
+ outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break outerLoop;
+ }
+ }
+ }
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ // If the name points to a package's name, use
+ // the package main instead.
+ pkgMain = getOwn(config.pkgs, name);
+
+ return pkgMain ? pkgMain : name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+
+ //Custom require that does not do map translation, since
+ //ID is "absolute", already mapped/resolved.
+ context.makeRequire(null, {
+ skipMap: true
+ })([id]);
+
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ // If nested plugin references, then do not try to
+ // normalize, as it will not normalize correctly. This
+ // places a restriction on resourceIds, and the longer
+ // term solution is not to normalize until plugins are
+ // loaded and all normalizations to allow for async
+ // loading of a loader plugin. But for now, fixes the
+ // common uses. Details in #1131
+ normalizedName = name.indexOf('!') === -1 ?
+ normalize(name, parentName, applyMap) :
+ name;
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ mod = getModule(depMap);
+ if (mod.error && name === 'error') {
+ fn(mod.error);
+ } else {
+ mod.on(name, fn);
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return (defined[mod.map.id] = mod.exports);
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return getOwn(config.config, mod.map.id) || {};
+ },
+ exports: mod.exports || (mod.exports = {})
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ delete enabledRegistry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ var map = mod.map,
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) ||
+ req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ // Favor return value over exports. If node/cjs in play,
+ // then will not have a return value anyway. Favor
+ // module.exports assignment over exports object.
+ if (this.map.isDefine && exports === undefined) {
+ cjsModule = this.module;
+ if (cjsModule) {
+ exports = cjsModule.exports;
+ } else if (this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = this.map.isDefine ? [this.map.id] : null;
+ err.requireType = this.map.isDefine ? 'define' : 'require';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id);
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ bundleId = getOwn(bundlesMap, this.map.id),
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ //If a paths config, then just load that file instead to
+ //resolve the plugin, as it is built into that paths layer.
+ if (bundleId) {
+ this.map.url = context.nameToUrl(bundleId);
+ this.load();
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ return onError(makeError('fromtexteval',
+ 'fromText eval for ' + id +
+ ' failed: ' + e,
+ e,
+ [id]));
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this;
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback));
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths since they require special processing,
+ //they are additive.
+ var shim = config.shim,
+ objs = {
+ paths: true,
+ bundles: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (!config[prop]) {
+ config[prop] = {};
+ }
+ mixin(config[prop], value, true, true);
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Reverse map the bundles
+ if (cfg.bundles) {
+ eachProp(cfg.bundles, function (value, prop) {
+ each(value, function (v) {
+ if (v !== prop) {
+ bundlesMap[v] = prop;
+ }
+ });
+ });
+ }
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location, name;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+
+ name = pkgObj.name;
+ location = pkgObj.location;
+ if (location) {
+ config.paths[name] = pkgObj.location;
+ }
+
+ //Save pointer to main module ID for pkg name.
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '');
+ });
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..';
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext, true);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ removeScript(id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ //Clean queued defines too. Go backwards
+ //in array so that the splices do not
+ //mess up the iteration.
+ eachReverse(defQueue, function(args, i) {
+ if(args[0] === id) {
+ defQueue.splice(i, 1);
+ }
+ });
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overridden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths, syms, i, parentModule, url,
+ parentPath, bundleId,
+ pkgMain = getOwn(config.pkgs, moduleName);
+
+ if (pkgMain) {
+ moduleName = pkgMain;
+ }
+
+ bundleId = getOwn(bundlesMap, moduleName);
+
+ if (bundleId) {
+ return context.nameToUrl(bundleId, ext, skipExt);
+ }
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError;
+
+ /**
+ * Creates the node for the load command. Only used in browser envs.
+ */
+ req.createNode = function (config, moduleName, url) {
+ var node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+ return node;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = req.createNode(config, moduleName, url);
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ } catch (e) {
+ context.onError(makeError('importscripts',
+ 'importScripts failed for ' +
+ moduleName + ' at ' + url,
+ e,
+ [moduleName]));
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser && !cfg.skipDataMain) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain;
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '');
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain;
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = null;
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = [];
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
diff --git a/devtools/client/jsonview/moz.build b/devtools/client/jsonview/moz.build
new file mode 100644
index 0000000000..8d0350ef3f
--- /dev/null
+++ b/devtools/client/jsonview/moz.build
@@ -0,0 +1,24 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += ["components", "css", "lib"]
+
+DevToolsModules(
+ "converter-child.js",
+ "Converter.sys.mjs",
+ "json-viewer.js",
+ "Sniffer.sys.mjs",
+ "viewer-config.js",
+)
+
+XPCOM_MANIFESTS += [
+ "components.conf",
+]
+
+BROWSER_CHROME_MANIFESTS += ["test/browser.ini"]
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "JSON Viewer")
diff --git a/devtools/client/jsonview/test/array_json.json b/devtools/client/jsonview/test/array_json.json
new file mode 100644
index 0000000000..a53a19fa70
--- /dev/null
+++ b/devtools/client/jsonview/test/array_json.json
@@ -0,0 +1 @@
+[{ "name": "jan" }, { "name": "honza" }, { "name": "odvarko" }]
diff --git a/devtools/client/jsonview/test/array_json.json^headers^ b/devtools/client/jsonview/test/array_json.json^headers^
new file mode 100644
index 0000000000..6010bfd188
--- /dev/null
+++ b/devtools/client/jsonview/test/array_json.json^headers^
@@ -0,0 +1 @@
+Content-Type: application/json; charset=utf-8
diff --git a/devtools/client/jsonview/test/browser.ini b/devtools/client/jsonview/test/browser.ini
new file mode 100644
index 0000000000..0acb44c6b3
--- /dev/null
+++ b/devtools/client/jsonview/test/browser.ini
@@ -0,0 +1,59 @@
+[DEFAULT]
+tags = devtools
+subsuite = devtools
+support-files =
+ array_json.json
+ array_json.json^headers^
+ csp_json.json
+ csp_json.json^headers^
+ empty.html
+ head.js
+ invalid_json.json
+ invalid_json.json^headers^
+ manifest_json.json
+ manifest_json.json^headers^
+ passthrough-sw.js
+ simple_json.json
+ simple_json.json^headers^
+ valid_json.json
+ valid_json.json^headers^
+ !/devtools/client/framework/test/head.js
+ !/devtools/client/shared/test/shared-head.js
+ !/devtools/client/shared/test/telemetry-test-helpers.js
+
+[browser_json_refresh.js]
+[browser_jsonview_bug_1380828.js]
+[browser_jsonview_chunked_json.js]
+skip-if = http3 # Bug 1829298
+support-files =
+ chunked_json.sjs
+[browser_jsonview_content_type.js]
+[browser_jsonview_copy_headers.js]
+[browser_jsonview_copy_json.js]
+[browser_jsonview_copy_rawdata.js]
+[browser_jsonview_csp_json.js]
+[browser_jsonview_data_blocking.js]
+[browser_jsonview_empty_object.js]
+[browser_jsonview_encoding.js]
+[browser_jsonview_filter.js]
+[browser_jsonview_filter_clear.js]
+[browser_jsonview_ignore_charset.js]
+[browser_jsonview_initial_focus.js]
+[browser_jsonview_invalid_json.js]
+[browser_jsonview_manifest.js]
+[browser_jsonview_nojs.js]
+[browser_jsonview_nul.js]
+[browser_jsonview_object-type.js]
+[browser_jsonview_row_selection.js]
+[browser_jsonview_save_json.js]
+skip-if = http3 # Bug 1829298
+support-files =
+ !/toolkit/content/tests/browser/common/mockTransfer.js
+[browser_jsonview_serviceworker.js]
+[browser_jsonview_slash.js]
+[browser_jsonview_theme.js]
+[browser_jsonview_url_linkification.js]
+[browser_jsonview_valid_json.js]
+[browser_jsonview_expand_collapse.js]
+skip-if =
+ os == 'linux' && bits == 64 && !debug # Bug 1794904
diff --git a/devtools/client/jsonview/test/browser_json_refresh.js b/devtools/client/jsonview/test/browser_json_refresh.js
new file mode 100644
index 0000000000..0fbebbae57
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_json_refresh.js
@@ -0,0 +1,97 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_FILE = "simple_json.json";
+
+add_task(async function () {
+ info("Test JSON refresh started");
+
+ // generate file:// URI for JSON file and load in new tab
+ const dir = getChromeDir(getResolvedURI(gTestPath));
+ dir.append(TEST_JSON_FILE);
+ dir.normalize();
+ const uri = Services.io.newFileURI(dir);
+ const tab = await addJsonViewTab(uri.spec);
+
+ // perform sanity checks for URI and principals in loadInfo
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ TEST_JSON_FILE }],
+ // eslint-disable-next-line no-shadow
+ async function ({ TEST_JSON_FILE }) {
+ const channel = content.docShell.currentDocumentChannel;
+ const channelURI = channel.URI.spec;
+ ok(
+ channelURI.startsWith("file://") && channelURI.includes(TEST_JSON_FILE),
+ "sanity: correct channel uri"
+ );
+ const contentPolicyType = channel.loadInfo.externalContentPolicyType;
+ is(
+ contentPolicyType,
+ Ci.nsIContentPolicy.TYPE_DOCUMENT,
+ "sanity: correct contentPolicyType"
+ );
+
+ const loadingPrincipal = channel.loadInfo.loadingPrincipal;
+ is(loadingPrincipal, null, "sanity: correct loadingPrincipal");
+ const triggeringPrincipal = channel.loadInfo.triggeringPrincipal;
+ ok(
+ triggeringPrincipal.isSystemPrincipal,
+ "sanity: correct triggeringPrincipal"
+ );
+ const principalToInherit = channel.loadInfo.principalToInherit;
+ ok(
+ principalToInherit.isNullPrincipal,
+ "sanity: correct principalToInherit"
+ );
+ ok(
+ content.document.nodePrincipal.isNullPrincipal,
+ "sanity: correct doc.nodePrincipal"
+ );
+ }
+ );
+
+ // reload the tab
+ await reloadBrowser();
+
+ // check principals in loadInfo are still correct
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ TEST_JSON_FILE }],
+ // eslint-disable-next-line no-shadow
+ async function ({ TEST_JSON_FILE }) {
+ // eslint-disable-line
+ const channel = content.docShell.currentDocumentChannel;
+ const channelURI = channel.URI.spec;
+ ok(
+ channelURI.startsWith("file://") && channelURI.includes(TEST_JSON_FILE),
+ "reloaded: correct channel uri"
+ );
+ const contentPolicyType = channel.loadInfo.externalContentPolicyType;
+ is(
+ contentPolicyType,
+ Ci.nsIContentPolicy.TYPE_DOCUMENT,
+ "reloaded: correct contentPolicyType"
+ );
+
+ const loadingPrincipal = channel.loadInfo.loadingPrincipal;
+ is(loadingPrincipal, null, "reloaded: correct loadingPrincipal");
+ const triggeringPrincipal = channel.loadInfo.triggeringPrincipal;
+ ok(
+ triggeringPrincipal.isSystemPrincipal,
+ "reloaded: correct triggeringPrincipal"
+ );
+ const principalToInherit = channel.loadInfo.principalToInherit;
+ ok(
+ principalToInherit.isNullPrincipal,
+ "reloaded: correct principalToInherit"
+ );
+ ok(
+ content.document.nodePrincipal.isNullPrincipal,
+ "reloaded: correct doc.nodePrincipal"
+ );
+ }
+ );
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_bug_1380828.js b/devtools/client/jsonview/test/browser_jsonview_bug_1380828.js
new file mode 100644
index 0000000000..6d698e8930
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_bug_1380828.js
@@ -0,0 +1,32 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const VALID_JSON_URL = URL_ROOT + "valid_json.json";
+const INVALID_JSON_URL = URL_ROOT + "invalid_json.json";
+const prettyPrintButtonClass = ".textPanelBox .toolbar button.prettyprint";
+
+add_task(async function () {
+ info("Test 'Pretty Print' button disappears on parsing invalid JSON");
+
+ const count = await testPrettyPrintButton(INVALID_JSON_URL);
+ is(count, 0, "There must be no pretty-print button for invalid json");
+});
+
+add_task(async function () {
+ info("Test 'Pretty Print' button is present on parsing valid JSON");
+
+ const count = await testPrettyPrintButton(VALID_JSON_URL);
+ is(count, 1, "There must be pretty-print button for valid json");
+});
+
+async function testPrettyPrintButton(url) {
+ await addJsonViewTab(url);
+
+ await selectJsonViewContentTab("rawdata");
+ info("Switched to Raw Data tab.");
+
+ const count = await getElementCount(prettyPrintButtonClass);
+ return count;
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_chunked_json.js b/devtools/client/jsonview/test/browser_jsonview_chunked_json.js
new file mode 100644
index 0000000000..56fe611486
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_chunked_json.js
@@ -0,0 +1,121 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT_SSL + "chunked_json.sjs";
+
+add_task(async function () {
+ info("Test chunked JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL, {
+ appReadyState: "interactive",
+ docReadyState: "loading",
+ });
+
+ is(
+ await getElementCount(".rawdata.is-active"),
+ 1,
+ "The Raw Data tab is selected."
+ );
+
+ // Write some text and check that it is displayed.
+ await write("[");
+ await checkText();
+
+ // Repeat just in case.
+ await write("1,");
+ await checkText();
+
+ is(
+ await getElementCount("button.prettyprint"),
+ 0,
+ "There is no pretty print button during load"
+ );
+
+ await selectJsonViewContentTab("json");
+ is(
+ await getElementText(".jsonPanelBox > .panelContent"),
+ "",
+ "There is no JSON tree"
+ );
+
+ await selectJsonViewContentTab("headers");
+ ok(
+ await getElementText(".headersPanelBox .netInfoHeadersTable"),
+ "The headers table has been filled."
+ );
+
+ // Write some text without being in Raw Data, then switch tab and check.
+ await write("2");
+ await selectJsonViewContentTab("rawdata");
+ await checkText();
+
+ // Add an array, when counting rows we will ensure it has been expanded automatically.
+ await write(",[3]]");
+ await checkText();
+
+ // Close the connection.
+
+ // When the ready state of the JSON View app changes, it triggers the
+ // custom event "AppReadyStateChange".
+ const appReady = BrowserTestUtils.waitForContentEvent(
+ gBrowser.selectedBrowser,
+ "AppReadyStateChange",
+ true,
+ null,
+ true
+ );
+ await server("close");
+ await appReady;
+
+ is(await getElementCount(".json.is-active"), 1, "The JSON tab is selected.");
+
+ is(
+ await getElementCount(".jsonPanelBox .treeTable .treeRow"),
+ 4,
+ "There is a tree with 4 rows."
+ );
+
+ await selectJsonViewContentTab("rawdata");
+ await checkText();
+
+ is(
+ await getElementCount("button.prettyprint"),
+ 1,
+ "There is a pretty print button."
+ );
+ await clickJsonNode("button.prettyprint");
+ await checkText(JSON.stringify(JSON.parse(data), null, 2));
+});
+
+let data = " ";
+async function write(text) {
+ data += text;
+ const onJsonViewUpdated = SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [],
+ () => {
+ return new Promise(resolve => {
+ const observer = new content.MutationObserver(() => resolve());
+ observer.observe(content.wrappedJSObject.JSONView.json, {
+ characterData: true,
+ });
+ });
+ }
+ );
+ await server("write", text);
+ await onJsonViewUpdated;
+}
+async function checkText(text = data) {
+ is(await getElementText(".textPanelBox .data"), text, "Got the right text.");
+}
+
+function server(action, value) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", TEST_JSON_URL + "?" + action + "=" + value);
+ xhr.addEventListener("load", resolve, { once: true });
+ xhr.send();
+ });
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_content_type.js b/devtools/client/jsonview/test/browser_jsonview_content_type.js
new file mode 100644
index 0000000000..c3298cc7d9
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_content_type.js
@@ -0,0 +1,100 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
+const handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
+ Ci.nsIHandlerService
+);
+
+const contentTypes = {
+ valid: [
+ "application/json",
+ "application/manifest+json",
+ "application/vnd.api+json",
+ "application/hal+json",
+ "application/json+json",
+ "application/whatever+json",
+ ],
+ invalid: [
+ "text/json",
+ "text/hal+json",
+ "application/jsona",
+ "application/whatever+jsona",
+ ],
+};
+
+add_task(async function () {
+ info("Test JSON content types started");
+
+ // Prevent saving files to disk.
+ const useDownloadDir = SpecialPowers.getBoolPref(
+ "browser.download.useDownloadDir"
+ );
+ SpecialPowers.setBoolPref("browser.download.useDownloadDir", false);
+ const { MockFilePicker } = SpecialPowers;
+ MockFilePicker.init(window);
+ MockFilePicker.returnValue = MockFilePicker.returnCancel;
+
+ for (const kind of Object.keys(contentTypes)) {
+ const isValid = kind === "valid";
+ for (const type of contentTypes[kind]) {
+ // Prevent "Open or Save" dialogs, which would make the test fail.
+ const mimeInfo = mimeSvc.getFromTypeAndExtension(type, null);
+ const exists = handlerSvc.exists(mimeInfo);
+ const { alwaysAskBeforeHandling } = mimeInfo;
+ mimeInfo.alwaysAskBeforeHandling = false;
+ handlerSvc.store(mimeInfo);
+
+ await testType(isValid, type);
+ await testType(isValid, type, ";foo=bar+json");
+
+ // Restore old nsIMIMEInfo
+ if (exists) {
+ Object.assign(mimeInfo, { alwaysAskBeforeHandling });
+ handlerSvc.store(mimeInfo);
+ } else {
+ handlerSvc.remove(mimeInfo);
+ }
+ }
+ }
+
+ // Restore old pref
+ registerCleanupFunction(function () {
+ MockFilePicker.cleanup();
+ SpecialPowers.setBoolPref(
+ "browser.download.useDownloadDir",
+ useDownloadDir
+ );
+ });
+});
+
+function testType(isValid, type, params = "") {
+ const TEST_JSON_URL = "data:" + type + params + ",[1,2,3]";
+ return addJsonViewTab(TEST_JSON_URL).then(
+ async function () {
+ ok(isValid, "The JSON Viewer should only load for valid content types.");
+ await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [type],
+ function (contentType) {
+ is(
+ content.document.contentType,
+ contentType,
+ "Got the right content type"
+ );
+ }
+ );
+
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 3, "There must be expected number of rows");
+ },
+ function () {
+ ok(
+ !isValid,
+ "The JSON Viewer should only not load for invalid content types."
+ );
+ }
+ );
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_headers.js b/devtools/client/jsonview/test/browser_jsonview_copy_headers.js
new file mode 100644
index 0000000000..faa6e43354
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_copy_headers.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "valid_json.json";
+
+add_task(async function () {
+ info("Test valid JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ // Select the RawData tab
+ await selectJsonViewContentTab("headers");
+
+ // Check displayed headers
+ const count = await getElementCount(".headersPanelBox .netHeadersGroup");
+ is(count, 2, "There must be two header groups");
+
+ const text = await getElementText(".headersPanelBox .netInfoHeadersTable");
+ isnot(text, "", "Headers text must not be empty");
+
+ const browser = gBrowser.selectedBrowser;
+
+ // Verify JSON copy into the clipboard.
+ await waitForClipboardPromise(
+ function setup() {
+ BrowserTestUtils.synthesizeMouseAtCenter(
+ ".headersPanelBox .toolbar button.copy",
+ {},
+ browser
+ );
+ },
+ function validator(value) {
+ return value.indexOf("application/json") > 0;
+ }
+ );
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_json.js b/devtools/client/jsonview/test/browser_jsonview_copy_json.js
new file mode 100644
index 0000000000..56c7b3ff75
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_copy_json.js
@@ -0,0 +1,34 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "simple_json.json";
+
+add_task(async function () {
+ info("Test copy JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const countBefore = await getElementCount(
+ ".jsonPanelBox .treeTable .treeRow"
+ );
+ ok(countBefore == 1, "There must be one row");
+
+ const text = await getElementText(".jsonPanelBox .treeTable .treeRow");
+ is(text, 'name"value"', "There must be proper JSON displayed");
+
+ // Verify JSON copy into the clipboard.
+ const value = '{ "name": "value" }\n';
+ const browser = gBrowser.selectedBrowser;
+ const selector = ".jsonPanelBox .toolbar button.copy";
+ await waitForClipboardPromise(
+ function setup() {
+ BrowserTestUtils.synthesizeMouseAtCenter(selector, {}, browser);
+ },
+ function validator(result) {
+ const str = normalizeNewLines(result);
+ return str == value;
+ }
+ );
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js b/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js
new file mode 100644
index 0000000000..0685b7c5d3
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js
@@ -0,0 +1,62 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "simple_json.json";
+
+const jsonText = '{ "name": "value" }\n';
+const prettyJson = '{\n "name": "value"\n}';
+
+add_task(async function () {
+ info("Test copy raw data started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ // Select the RawData tab
+ await selectJsonViewContentTab("rawdata");
+
+ // Check displayed JSON
+ const text = await getElementText(".textPanelBox .data");
+ is(text, jsonText, "Proper JSON must be displayed in DOM");
+
+ const browser = gBrowser.selectedBrowser;
+
+ // Verify JSON copy into the clipboard.
+ await waitForClipboardPromise(function setup() {
+ BrowserTestUtils.synthesizeMouseAtCenter(
+ ".textPanelBox .toolbar button.copy",
+ {},
+ browser
+ );
+ }, jsonText);
+
+ // Click 'Pretty Print' button
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ ".textPanelBox .toolbar button.prettyprint",
+ {},
+ browser
+ );
+
+ let prettyText = await getElementText(".textPanelBox .data");
+ prettyText = normalizeNewLines(prettyText);
+ ok(
+ prettyText.startsWith(prettyJson),
+ "Pretty printed JSON must be displayed"
+ );
+
+ // Verify JSON copy into the clipboard.
+ await waitForClipboardPromise(
+ function setup() {
+ BrowserTestUtils.synthesizeMouseAtCenter(
+ ".textPanelBox .toolbar button.copy",
+ {},
+ browser
+ );
+ },
+ function validator(value) {
+ const str = normalizeNewLines(value);
+ return str == prettyJson;
+ }
+ );
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_csp_json.js b/devtools/client/jsonview/test/browser_jsonview_csp_json.js
new file mode 100644
index 0000000000..4416bccf15
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_csp_json.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "csp_json.json";
+
+add_task(async function () {
+ info("Test CSP JSON started");
+
+ const tab = await addJsonViewTab(TEST_JSON_URL);
+
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 1, "There must be one row");
+
+ // The JSON Viewer alters the CSP, but the displayed header should be the original one
+ await selectJsonViewContentTab("headers");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ const responseHeaders = content.document.querySelector(".netHeadersGroup");
+ const names = responseHeaders.querySelectorAll(".netInfoParamName");
+ let found = false;
+ for (const name of names) {
+ if (name.textContent.toLowerCase() == "content-security-policy") {
+ ok(!found, "The CSP header only appears once");
+ found = true;
+ const value = name.nextElementSibling.textContent;
+ const expected = "default-src 'none'; base-uri 'none';";
+ is(value, expected, "The CSP value has not been altered");
+ }
+ }
+ ok(found, "The CSP header is present");
+ });
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_data_blocking.js b/devtools/client/jsonview/test/browser_jsonview_data_blocking.js
new file mode 100644
index 0000000000..f36d39dcc8
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_data_blocking.js
@@ -0,0 +1,174 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_PATH = getRootDirectory(gTestPath).replace(
+ "chrome://mochitests/content",
+ "http://example.com"
+);
+
+const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view";
+const nullP = Services.scriptSecurityManager.createNullPrincipal({});
+
+// We need 3 levels of nesting just to get to run something against a content
+// page, so the devtools limit of 4 levels of nesting don't help:
+/* eslint max-nested-callbacks: 0 */
+
+/**
+ * Check that we don't expose a JSONView object on data: URI windows where
+ * we block the load.
+ */
+add_task(async function test_blocked_data_exposure() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["security.data_uri.block_toplevel_data_uri_navigations", true]],
+ });
+ await BrowserTestUtils.withNewTab(TEST_PATH + "empty.html", async browser => {
+ const tabCount = gBrowser.tabs.length;
+ await SpecialPowers.spawn(browser, [], function () {
+ content.w = content.window.open(
+ "data:application/vnd.mozilla.json.view,1",
+ "_blank"
+ );
+ ok(
+ !Cu.waiveXrays(content.w).JSONView,
+ "Should not have created a JSON View object"
+ );
+ // We need to wait for the JSON view machinery to actually have a chance to run.
+ // We have no way to detect that it has or hasn't, so a setTimeout is the best we
+ // can do, unfortunately.
+ return new Promise(resolve => {
+ content.setTimeout(function () {
+ // Putting the resolve before the check to avoid JS errors potentially causing
+ // the test to time out.
+ resolve();
+ ok(
+ !Cu.waiveXrays(content.w).JSONView,
+ "Should still not have a JSON View object"
+ );
+ }, 1000);
+ });
+ });
+ // Without this, if somehow the data: protocol blocker stops working, the
+ // test would just keep passing.
+ is(
+ tabCount,
+ gBrowser.tabs.length,
+ "Haven't actually opened a new window/tab"
+ );
+ });
+});
+
+/**
+ * Check that aborted channels also abort sending data from the stream converter.
+ */
+add_task(async function test_converter_abort_should_stop_data_sending() {
+ const loadInfo = NetUtil.newChannel({
+ uri: Services.io.newURI("data:text/plain,"),
+ loadingPrincipal: nullP,
+ securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
+ contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER,
+ }).loadInfo;
+ // Stub all the things.
+ const chan = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIChannel",
+ "nsIWritablePropertyBag",
+ ]),
+ URI: Services.io.newURI("data:application/json,{}"),
+ // loadinfo is builtinclass, need to actually have one:
+ loadInfo,
+ notificationCallbacks: {
+ QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]),
+ getInterface() {
+ // We want a loadcontext here, which is also builtinclass, can't stub.
+ return docShell;
+ },
+ },
+ status: Cr.NS_OK,
+ setProperty() {},
+ };
+ let onStartFired = false;
+ const listener = {
+ QueryInterface: ChromeUtils.generateQI(["nsIStreamListener"]),
+ onStartRequest() {
+ onStartFired = true;
+ // This should force the converter to abort, too:
+ chan.status = Cr.NS_BINDING_ABORTED;
+ },
+ onDataAvailable() {
+ ok(false, "onDataAvailable should never fire");
+ },
+ };
+ const conv = Cc[
+ "@mozilla.org/streamconv;1?from=" + JSON_VIEW_MIME_TYPE + "&to=*/*"
+ ].createInstance(Ci.nsIStreamConverter);
+ conv.asyncConvertData(
+ "application/vnd.mozilla.json.view",
+ "text/html",
+ listener,
+ null
+ );
+ conv.onStartRequest(chan);
+ ok(onStartFired, "Should have fired onStartRequest");
+});
+
+/**
+ * Check that principal mismatches break things. Note that we're stubbing
+ * the window associated with the channel to be a browser window; the
+ * converter should be bailing out because the window's principal won't
+ * match the null principal to which the converter tries to reset the
+ * inheriting principal of the channel.
+ */
+add_task(async function test_converter_principal_needs_matching() {
+ const loadInfo = NetUtil.newChannel({
+ uri: Services.io.newURI("data:text/plain,"),
+ loadingPrincipal: nullP,
+ securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
+ contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER,
+ }).loadInfo;
+ // Stub all the things.
+ const chan = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIChannel",
+ "nsIWritablePropertyBag",
+ ]),
+ URI: Services.io.newURI("data:application/json,{}"),
+ // loadinfo is builtinclass, need to actually have one:
+ loadInfo,
+ notificationCallbacks: {
+ QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]),
+ getInterface() {
+ // We want a loadcontext here, which is also builtinclass, can't stub.
+ return docShell;
+ },
+ },
+ status: Cr.NS_OK,
+ setProperty() {},
+ cancel(arg) {
+ this.status = arg;
+ },
+ };
+ let onStartFired = false;
+ const listener = {
+ QueryInterface: ChromeUtils.generateQI(["nsIStreamListener"]),
+ onStartRequest() {
+ onStartFired = true;
+ },
+ onDataAvailable() {
+ ok(false, "onDataAvailable should never fire");
+ },
+ };
+ const conv = Cc[
+ "@mozilla.org/streamconv;1?from=" + JSON_VIEW_MIME_TYPE + "&to=*/*"
+ ].createInstance(Ci.nsIStreamConverter);
+ conv.asyncConvertData(
+ "application/vnd.mozilla.json.view",
+ "text/html",
+ listener,
+ null
+ );
+ conv.onStartRequest(chan);
+ ok(onStartFired, "Should have fired onStartRequest");
+ is(chan.status, Cr.NS_BINDING_ABORTED, "Should have been aborted.");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_empty_object.js b/devtools/client/jsonview/test/browser_jsonview_empty_object.js
new file mode 100644
index 0000000000..af3dfbc007
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_empty_object.js
@@ -0,0 +1,48 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+function testRootObject(objExpr, summary = objExpr) {
+ return async function () {
+ info("Test JSON with root empty object " + objExpr + " started");
+
+ const TEST_JSON_URL = "data:application/json," + objExpr;
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const objectText = await getElementText(".jsonPanelBox .panelContent");
+ is(objectText, summary, "The root object " + objExpr + " is visible");
+ };
+}
+
+function testNestedObject(objExpr, summary = objExpr) {
+ return async function () {
+ info("Test JSON with nested empty object " + objExpr + " started");
+
+ const TEST_JSON_URL = "data:application/json,[" + objExpr + "]";
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const objectCellCount = await getElementCount(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellCount, 1, "There must be one object cell");
+
+ const objectCellText = await getElementText(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellText, summary, objExpr + " has a visible summary");
+
+ // Collapse auto-expanded node.
+ await clickJsonNode(".jsonPanelBox .treeTable .treeLabel");
+
+ const textAfter = await getElementText(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(textAfter, summary, objExpr + " still has a visible summary");
+ };
+}
+
+add_task(testRootObject("null"));
+add_task(testNestedObject("null"));
+add_task(testNestedObject("[]"));
+add_task(testNestedObject("{}"));
diff --git a/devtools/client/jsonview/test/browser_jsonview_encoding.js b/devtools/client/jsonview/test/browser_jsonview_encoding.js
new file mode 100644
index 0000000000..be49af39d2
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_encoding.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test JSON encoding started");
+
+ const bom = "%EF%BB%BF"; // UTF-8 BOM
+ const tests = [
+ {
+ input: bom,
+ output: "",
+ },
+ {
+ input: "%FE%FF", // UTF-16BE BOM
+ output: "\uFFFD\uFFFD",
+ },
+ {
+ input: "%FF%FE", // UTF-16LE BOM
+ output: "\uFFFD\uFFFD",
+ },
+ {
+ input: bom + "%30",
+ output: "0",
+ },
+ {
+ input: bom + bom,
+ output: "\uFEFF",
+ },
+ {
+ input: "%00%61",
+ output: "\u0000a",
+ },
+ {
+ input: "%61%00",
+ output: "a\u0000",
+ },
+ {
+ input: "%30%FF",
+ output: "0�",
+ },
+ {
+ input: "%C3%A0",
+ output: "à",
+ },
+ {
+ input: "%E2%9D%A4",
+ output: "❤",
+ },
+ {
+ input: "%F0%9F%9A%80",
+ output: "🚀",
+ },
+ ];
+
+ for (const { input, output } of tests) {
+ info("Test decoding of " + JSON.stringify(input) + ".");
+
+ await addJsonViewTab("data:application/json," + input);
+ await selectJsonViewContentTab("rawdata");
+
+ // Check displayed data.
+ const data = await getElementText(".textPanelBox .data");
+ is(data, output, "The right data has been received.");
+ }
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_expand_collapse.js b/devtools/client/jsonview/test/browser_jsonview_expand_collapse.js
new file mode 100644
index 0000000000..6b681ff0cc
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_expand_collapse.js
@@ -0,0 +1,61 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+XPCOMUtils.defineLazyGetter(this, "jsonViewStrings", () => {
+ return Services.strings.createBundle(
+ "chrome://devtools/locale/jsonview.properties"
+ );
+});
+
+const TEST_JSON_URL = URL_ROOT + "array_json.json";
+const EXPAND_THRESHOLD = 100 * 1024;
+
+add_task(async function () {
+ info("Test expand/collapse small JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ /* Initial sanity check */
+ const countBefore = await getElementCount(".treeRow");
+ is(countBefore, 6, "There must be six rows");
+
+ /* Test the "Collapse All" button */
+ let selector = ".jsonPanelBox .toolbar button.collapse";
+ await clickJsonNode(selector);
+ let countAfter = await getElementCount(".treeRow");
+ is(countAfter, 3, "There must be three rows");
+
+ /* Test the "Expand All" button */
+ selector = ".jsonPanelBox .toolbar button.expand";
+ is(
+ await getElementText(selector),
+ jsonViewStrings.GetStringFromName("jsonViewer.ExpandAll"),
+ "Expand button doesn't warn that the action will be slow"
+ );
+ await clickJsonNode(selector);
+ countAfter = await getElementCount(".treeRow");
+ is(countAfter, 6, "There must be six expanded rows");
+});
+
+add_task(async function () {
+ info("Test expand button for big JSON started");
+
+ const json = JSON.stringify({
+ data: Array(1e5)
+ .fill()
+ .map(x => "hoot"),
+ status: "ok",
+ });
+ ok(
+ json.length > EXPAND_THRESHOLD,
+ "The generated JSON must be larger than 100kB"
+ );
+ await addJsonViewTab("data:application/json," + json);
+ is(
+ await getElementText(".jsonPanelBox .toolbar button.expand"),
+ jsonViewStrings.GetStringFromName("jsonViewer.ExpandAllSlow"),
+ "Expand button warns that the action will be slow"
+ );
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_filter.js b/devtools/client/jsonview/test/browser_jsonview_filter.js
new file mode 100644
index 0000000000..1dd093da5b
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_filter.js
@@ -0,0 +1,27 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "array_json.json";
+
+add_task(async function () {
+ info("Test valid JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 6, "There must be expected number of rows");
+
+ // XXX use proper shortcut to focus the filter box
+ // as soon as bug Bug 1178771 is fixed.
+ await sendString("h", ".jsonPanelBox .searchBox");
+
+ // The filtering is done asynchronously so, we need to wait.
+ await waitForFilter();
+
+ const hiddenCount = await getElementCount(
+ ".jsonPanelBox .treeTable .treeRow.hidden"
+ );
+ is(hiddenCount, 4, "There must be expected number of hidden rows");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_filter_clear.js b/devtools/client/jsonview/test/browser_jsonview_filter_clear.js
new file mode 100644
index 0000000000..70ece7ee03
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_filter_clear.js
@@ -0,0 +1,85 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "array_json.json";
+const filterClearButton = "button.devtools-searchinput-clear";
+
+function clickAndWaitForFilterClear(selector) {
+ return SpecialPowers.spawn(gBrowser.selectedBrowser, [selector], sel => {
+ content.document.querySelector(sel).click();
+
+ const rows = Array.from(
+ content.document.querySelectorAll(".jsonPanelBox .treeTable .treeRow")
+ );
+
+ // If there are no hiddens rows
+ if (!rows.some(r => r.classList.contains("hidden"))) {
+ info("The view has been cleared, no need for mutationObserver");
+ return Promise.resolve();
+ }
+
+ return new Promise(resolve => {
+ // Wait until we have 0 hidden rows
+ const observer = new content.MutationObserver(function (mutations) {
+ info("New mutation ! ");
+ info(`${mutations}`);
+ for (let i = 0; i < mutations.length; i++) {
+ const mutation = mutations[i];
+ info(`type: ${mutation.type}`);
+ info(`attributeName: ${mutation.attributeName}`);
+ info(`attributeNamespace: ${mutation.attributeNamespace}`);
+ info(`oldValue: ${mutation.oldValue}`);
+ if (mutation.attributeName == "class") {
+ if (!rows.some(r => r.classList.contains("hidden"))) {
+ info("resolving mutationObserver");
+ observer.disconnect();
+ resolve();
+ break;
+ }
+ }
+ }
+ });
+
+ const parent = content.document.querySelector("tbody");
+ observer.observe(parent, { attributes: true, subtree: true });
+ });
+ });
+}
+
+add_task(async function () {
+ info("Test filter input is cleared when pressing the clear button");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ // Type "honza" in the filter input
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 6, "There must be expected number of rows");
+ await sendString("honza", ".jsonPanelBox .searchBox");
+ await waitForFilter();
+
+ const filterInputValue = await getFilterInputValue();
+ is(filterInputValue, "honza", "Filter input shoud be filled");
+
+ // Check the json is filtered
+ const hiddenCount = await getElementCount(
+ ".jsonPanelBox .treeTable .treeRow.hidden"
+ );
+ is(hiddenCount, 4, "There must be expected number of hidden rows");
+
+ info("Click on the close button");
+ await clickAndWaitForFilterClear(filterClearButton);
+
+ // Check the json is not filtered and the filter input is empty
+ const newfilterInputValue = await getFilterInputValue();
+ is(newfilterInputValue, "", "Filter input should be empty");
+ const newCount = await getElementCount(
+ ".jsonPanelBox .treeTable .treeRow.hidden"
+ );
+ is(newCount, 0, "There must be expected number of rows");
+});
+
+function getFilterInputValue() {
+ return getElementAttr(".devtools-filterinput", "value");
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_ignore_charset.js b/devtools/client/jsonview/test/browser_jsonview_ignore_charset.js
new file mode 100644
index 0000000000..ffd00a35e3
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_ignore_charset.js
@@ -0,0 +1,18 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test ignored charset parameter started");
+
+ const encodedChar = "%E2%9D%A4"; // In UTF-8 this is a heavy black heart
+ const result = "❤";
+ const TEST_JSON_URL = "data:application/json;charset=ANSI," + encodedChar;
+
+ await addJsonViewTab(TEST_JSON_URL);
+ await selectJsonViewContentTab("rawdata");
+
+ const text = await getElementText(".textPanelBox .data");
+ is(text, result, "The charset parameter is ignored and UTF-8 is used.");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_initial_focus.js b/devtools/client/jsonview/test/browser_jsonview_initial_focus.js
new file mode 100644
index 0000000000..71b0623ce5
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_initial_focus.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const VALID_JSON_URL = URL_ROOT + "valid_json.json";
+
+add_task(async function () {
+ info("Test focus JSON view started");
+ await addJsonViewTab(VALID_JSON_URL);
+
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], async () => {
+ const scroller = content.document.getElementById("json-scrolling-panel");
+ ok(scroller, "Found the scrollable area");
+ is(
+ content.document.activeElement,
+ scroller,
+ "Scrollable area initially focused"
+ );
+ });
+ await reloadBrowser();
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], async () => {
+ const scroller = await ContentTaskUtils.waitForCondition(
+ () => content.document.getElementById("json-scrolling-panel"),
+ "Wait for the panel to be loaded"
+ );
+ is(
+ content.document.activeElement,
+ scroller,
+ "Scrollable area focused after reload"
+ );
+ });
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_invalid_json.js b/devtools/client/jsonview/test/browser_jsonview_invalid_json.js
new file mode 100644
index 0000000000..461030959b
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_invalid_json.js
@@ -0,0 +1,18 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "invalid_json.json";
+
+add_task(async function () {
+ info("Test invalid JSON started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ ok(count == 0, "There must be no row");
+
+ const text = await getElementText(".jsonPanelBox .jsonParseError");
+ ok(text, "There must be an error description");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_manifest.js b/devtools/client/jsonview/test/browser_jsonview_manifest.js
new file mode 100644
index 0000000000..8072324cf1
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_manifest.js
@@ -0,0 +1,15 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "manifest_json.json";
+
+add_task(async function () {
+ info("Test manifest JSON file started");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 37, "There must be expected number of rows");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_nojs.js b/devtools/client/jsonview/test/browser_jsonview_nojs.js
new file mode 100644
index 0000000000..38459617a2
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_nojs.js
@@ -0,0 +1,26 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test JSON without JavaScript started.");
+
+ const oldPref = Services.prefs.getBoolPref("javascript.enabled");
+ Services.prefs.setBoolPref("javascript.enabled", false);
+
+ const TEST_JSON_URL = "data:application/json,[1,2,3]";
+
+ // "uninitialized" will be the last app readyState because JS is disabled.
+ await addJsonViewTab(TEST_JSON_URL, { appReadyState: "uninitialized" });
+
+ info("Checking visible text contents.");
+
+ const text = await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {
+ const element = content.document.querySelector("html");
+ return element ? element.innerText : null;
+ });
+ is(text, "[1,2,3]", "The raw source should be visible.");
+
+ Services.prefs.setBoolPref("javascript.enabled", oldPref);
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_nul.js b/devtools/client/jsonview/test/browser_jsonview_nul.js
new file mode 100644
index 0000000000..746846796b
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_nul.js
@@ -0,0 +1,15 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test JSON with NUL started.");
+
+ const TEST_JSON_URL = 'data:application/json,"foo_%00_bar"';
+ await addJsonViewTab(TEST_JSON_URL);
+
+ await selectJsonViewContentTab("rawdata");
+ const rawData = await getElementText(".textPanelBox .data");
+ is(rawData, '"foo_\u0000_bar"', "The NUL character has been preserved.");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_object-type.js b/devtools/client/jsonview/test/browser_jsonview_object-type.js
new file mode 100644
index 0000000000..08b9ed865c
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_object-type.js
@@ -0,0 +1,25 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ELLIPSIS } = require("resource://devtools/shared/l10n.js");
+
+add_task(async function () {
+ info("Test Object type property started");
+
+ const TEST_JSON_URL = 'data:application/json,{"x":{"type":"string"}}';
+ await addJsonViewTab(TEST_JSON_URL);
+
+ let count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 2, "There must be two rows");
+
+ // Collapse auto-expanded node.
+ await clickJsonNode(".jsonPanelBox .treeTable .treeLabel");
+
+ count = await getElementCount(".jsonPanelBox .treeTable .treeRow");
+ is(count, 1, "There must be one row");
+
+ const label = await getElementText(".jsonPanelBox .treeTable .objectCell");
+ is(label, `{${ELLIPSIS}}`, "The label must be indicating an object");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_row_selection.js b/devtools/client/jsonview/test/browser_jsonview_row_selection.js
new file mode 100644
index 0000000000..300ac40a03
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_row_selection.js
@@ -0,0 +1,245 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test 1 JSON row selection started");
+
+ // Create a tall JSON so that there is a scrollbar.
+ const numRows = 1e3;
+ const json = JSON.stringify(
+ Array(numRows)
+ .fill()
+ .map((_, i) => i)
+ );
+ const tab = await addJsonViewTab("data:application/json," + json);
+
+ is(
+ await getElementCount(".treeRow"),
+ numRows,
+ "Got the expected number of rows."
+ );
+ await assertRowSelected(null);
+
+ // Focus the tree and select first row.
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const tree = content.document.querySelector(".treeTable");
+ tree.focus();
+ is(tree, content.document.activeElement, "Tree should be focused");
+ content.document.querySelector(".treeRow:nth-child(1)").click();
+ });
+ await assertRowSelected(1);
+
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ ok(scroller.clientHeight < scroller.scrollHeight, "There is a scrollbar.");
+ is(scroller.scrollTop, 0, "Initially scrolled to the top.");
+ });
+
+ // Select last row.
+ await BrowserTestUtils.synthesizeKey("VK_END", {}, tab.linkedBrowser);
+ await assertRowSelected(numRows);
+
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ is(
+ scroller.scrollTop + scroller.clientHeight,
+ scroller.scrollHeight,
+ "Scrolled to the bottom."
+ );
+ // Click to select 2nd row.
+ content.document.querySelector(".treeRow:nth-child(2)").click();
+ });
+ await assertRowSelected(2);
+
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ ok(scroller.scrollTop > 0, "Not scrolled to the top.");
+ // Synthesize up arrow key to select first row.
+ content.document.querySelector(".treeTable").focus();
+ });
+ await BrowserTestUtils.synthesizeKey("VK_UP", {}, tab.linkedBrowser);
+ await assertRowSelected(1);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ is(scroller.scrollTop, 0, "Scrolled to the top.");
+ });
+});
+
+add_task(async function () {
+ info("Test 2 JSON row selection started");
+
+ const numRows = 4;
+ const tab = await addJsonViewTab("data:application/json,[0,1,2,3]");
+
+ is(
+ await getElementCount(".treeRow"),
+ numRows,
+ "Got the expected number of rows."
+ );
+ await assertRowSelected(null);
+
+ // Click to select first row.
+ await clickJsonNode(".treeRow:first-child");
+ await assertRowSelected(1);
+
+ // Synthesize multiple down arrow keydowns to select following rows.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], function () {
+ content.document.querySelector(".treeTable").focus();
+ });
+ for (let i = 2; i < numRows; ++i) {
+ await BrowserTestUtils.synthesizeKey(
+ "VK_DOWN",
+ { type: "keydown" },
+ tab.linkedBrowser
+ );
+ await assertRowSelected(i);
+ }
+
+ // Now synthesize the keyup, this shouldn't change selected row.
+ await BrowserTestUtils.synthesizeKey(
+ "VK_DOWN",
+ { type: "keyup" },
+ tab.linkedBrowser
+ );
+ await wait(500);
+ await assertRowSelected(numRows - 1);
+
+ // Finally, synthesize keydown with a modifier, this also shouldn't change selected row.
+ await BrowserTestUtils.synthesizeKey(
+ "VK_DOWN",
+ { type: "keydown", shiftKey: true },
+ tab.linkedBrowser
+ );
+ await wait(500);
+ await assertRowSelected(numRows - 1);
+});
+
+add_task(async function () {
+ info("Test 3 JSON row selection started");
+
+ // Create a JSON with a row taller than the panel.
+ const json = JSON.stringify([0, "a ".repeat(1e4), 1]);
+ const tab = await addJsonViewTab("data:application/json," + encodeURI(json));
+
+ is(await getElementCount(".treeRow"), 3, "Got the expected number of rows.");
+ await assertRowSelected(null);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ const row = content.document.querySelector(".treeRow:nth-child(2)");
+ ok(
+ scroller.clientHeight < row.clientHeight,
+ "The row is taller than the scroller."
+ );
+ is(scroller.scrollTop, 0, "Initially scrolled to the top.");
+
+ // Select the tall row.
+ content.document.querySelector(".treeTable").focus();
+ row.click();
+ });
+ await assertRowSelected(2);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ is(
+ scroller.scrollTop,
+ 0,
+ "When the row is visible, do not scroll on click."
+ );
+ });
+
+ // Select the last row.
+ await BrowserTestUtils.synthesizeKey("VK_DOWN", {}, tab.linkedBrowser);
+ await assertRowSelected(3);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ is(
+ scroller.scrollTop + scroller.offsetHeight,
+ scroller.scrollHeight,
+ "Scrolled to the bottom."
+ );
+
+ // Select the tall row.
+ const row = content.document.querySelector(".treeRow:nth-child(2)");
+ row.click();
+ });
+
+ await assertRowSelected(2);
+ const scroll = await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [],
+ function () {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ const row = content.document.querySelector(".treeRow:nth-child(2)");
+ is(
+ scroller.scrollTop + scroller.offsetHeight,
+ scroller.scrollHeight,
+ "Scrolled to the bottom. When the row is visible, do not scroll on click."
+ );
+
+ // Scroll up a bit, so that both the top and bottom of the row are not visible.
+ const scrollPos = (scroller.scrollTop = Math.ceil(
+ (scroller.scrollTop + row.offsetTop) / 2
+ ));
+ ok(
+ scroller.scrollTop > row.offsetTop,
+ "The top of the row is not visible."
+ );
+ ok(
+ scroller.scrollTop + scroller.offsetHeight <
+ row.offsetTop + row.offsetHeight,
+ "The bottom of the row is not visible."
+ );
+
+ // Select the tall row.
+ row.click();
+ return scrollPos;
+ }
+ );
+
+ await assertRowSelected(2);
+ await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [scroll],
+ function (scrollPos) {
+ const scroller = content.document.querySelector(
+ ".jsonPanelBox .panelContent"
+ );
+ is(scroller.scrollTop, scrollPos, "Scroll did not change");
+ }
+ );
+});
+
+async function assertRowSelected(rowNum) {
+ const idx = await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [],
+ function () {
+ return [].indexOf.call(
+ content.document.querySelectorAll(".treeRow"),
+ content.document.querySelector(".treeRow.selected")
+ );
+ }
+ );
+ is(
+ idx + 1,
+ +rowNum,
+ `${rowNum ? "The row #" + rowNum : "No row"} is selected.`
+ );
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_save_json.js b/devtools/client/jsonview/test/browser_jsonview_save_json.js
new file mode 100644
index 0000000000..506967df00
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_save_json.js
@@ -0,0 +1,159 @@
+/* eslint-disable no-unused-vars, no-undef */
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const saveButton = "button.save";
+const prettifyButton = "button.prettyprint";
+
+const { MockFilePicker } = SpecialPowers;
+MockFilePicker.init(window);
+MockFilePicker.returnValue = MockFilePicker.returnOK;
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
+ this
+);
+
+function awaitSavedFileContents(name, ext) {
+ return new Promise((resolve, reject) => {
+ MockFilePicker.showCallback = fp => {
+ try {
+ ok(true, "File picker was opened");
+ const fileName = fp.defaultString;
+ is(
+ fileName,
+ name,
+ "File picker should provide the correct default filename."
+ );
+ is(
+ fp.defaultExtension,
+ ext,
+ "File picker should provide the correct default file extension."
+ );
+ const destFile = destDir.clone();
+ destFile.append(fileName);
+ MockFilePicker.setFiles([destFile]);
+ MockFilePicker.showCallback = null;
+ mockTransferCallback = async function (downloadSuccess) {
+ try {
+ ok(
+ downloadSuccess,
+ "JSON should have been downloaded successfully"
+ );
+ ok(destFile.exists(), "The downloaded file should exist.");
+ const { path } = destFile;
+ await BrowserTestUtils.waitForCondition(() => IOUtils.exists(path));
+ await BrowserTestUtils.waitForCondition(async () => {
+ const { size } = await IOUtils.stat(path);
+ return size > 0;
+ });
+ const buffer = await IOUtils.read(path);
+ resolve(new TextDecoder().decode(buffer));
+ } catch (error) {
+ reject(error);
+ }
+ };
+ } catch (error) {
+ reject(error);
+ }
+ };
+ });
+}
+
+function createTemporarySaveDirectory() {
+ const saveDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
+ saveDir.append("jsonview-testsavedir");
+ if (!saveDir.exists()) {
+ info("Creating temporary save directory.");
+ saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
+ }
+ info("Temporary save directory: " + saveDir.path);
+ return saveDir;
+}
+
+const destDir = createTemporarySaveDirectory();
+mockTransferRegisterer.register();
+MockFilePicker.displayDirectory = destDir;
+registerCleanupFunction(function () {
+ mockTransferRegisterer.unregister();
+ MockFilePicker.cleanup();
+ destDir.remove(true);
+ ok(!destDir.exists(), "Destination dir should be removed");
+});
+
+add_task(async function () {
+ info("Test 1 save JSON started");
+
+ const JSON_FILE = "simple_json.json";
+ const TEST_JSON_URL = URL_ROOT + JSON_FILE;
+ const tab = await addJsonViewTab(TEST_JSON_URL);
+
+ const response = await fetch(new Request(TEST_JSON_URL));
+
+ info("Fetched JSON contents.");
+ const rawJSON = await response.text();
+ const prettyJSON = JSON.stringify(JSON.parse(rawJSON), null, " ");
+ isnot(
+ rawJSON,
+ prettyJSON,
+ "Original and prettified JSON should be different."
+ );
+
+ // Attempt to save original JSON via saveBrowser (ctrl/cmd+s or "Save Page As" command).
+ let data = awaitSavedFileContents(JSON_FILE, "json");
+ saveBrowser(tab.linkedBrowser);
+ is(await data, rawJSON, "Original JSON contents should have been saved.");
+
+ // Attempt to save original JSON via "Save" button
+ data = awaitSavedFileContents(JSON_FILE, "json");
+ await clickJsonNode(saveButton);
+ info("Clicked Save button.");
+ is(await data, rawJSON, "Original JSON contents should have been saved.");
+
+ // Attempt to save prettified JSON via "Save" button
+ await selectJsonViewContentTab("rawdata");
+ info("Switched to Raw Data tab.");
+ await clickJsonNode(prettifyButton);
+ info("Clicked Pretty Print button.");
+ data = awaitSavedFileContents(JSON_FILE, "json");
+ await clickJsonNode(saveButton);
+ info("Clicked Save button.");
+ is(
+ await data,
+ prettyJSON,
+ "Prettified JSON contents should have been saved."
+ );
+
+ // saveBrowser should still save original contents.
+ data = awaitSavedFileContents(JSON_FILE, "json");
+ saveBrowser(tab.linkedBrowser);
+ is(await data, rawJSON, "Original JSON contents should have been saved.");
+});
+
+add_task(async function () {
+ info("Test 2 save JSON started");
+
+ const TEST_JSON_URL = "data:application/json,2";
+ await addJsonViewTab(TEST_JSON_URL);
+
+ info("Checking that application/json adds .json extension by default.");
+ const data = awaitSavedFileContents("Untitled.json", "json");
+ await clickJsonNode(saveButton);
+ info("Clicked Save button.");
+ is(await data, "2", "JSON contents should have been saved.");
+});
+
+add_task(async function () {
+ info("Test 3 save JSON started");
+
+ const TEST_JSON_URL = "data:application/manifest+json,3";
+ await addJsonViewTab(TEST_JSON_URL);
+
+ info("Checking that application/manifest+json does not add .json extension.");
+ const data = awaitSavedFileContents("Untitled", null);
+ await clickJsonNode(saveButton);
+ info("Clicked Save button.");
+ is(await data, "3", "JSON contents should have been saved.");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_serviceworker.js b/devtools/client/jsonview/test/browser_jsonview_serviceworker.js
new file mode 100644
index 0000000000..37c407ecd4
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_serviceworker.js
@@ -0,0 +1,89 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT_SSL + "valid_json.json";
+const EMPTY_PAGE = URL_ROOT_SSL + "empty.html";
+const SW = URL_ROOT_SSL + "passthrough-sw.js";
+
+add_task(async function () {
+ info("Test valid JSON with service worker started");
+
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["dom.serviceWorkers.exemptFromPerDomainMax", true],
+ ["dom.serviceWorkers.enabled", true],
+ ["dom.serviceWorkers.testing.enabled", true],
+ ],
+ });
+
+ const swTab = BrowserTestUtils.addTab(gBrowser, EMPTY_PAGE);
+ const browser = gBrowser.getBrowserForTab(swTab);
+ await BrowserTestUtils.browserLoaded(browser);
+ await SpecialPowers.spawn(
+ browser,
+ [{ script: SW, scope: TEST_JSON_URL }],
+ async opts => {
+ const reg = await content.navigator.serviceWorker.register(opts.script, {
+ scope: opts.scope,
+ });
+ return new content.window.Promise(resolve => {
+ const worker = reg.installing;
+ if (worker.state === "activated") {
+ resolve();
+ return;
+ }
+ worker.addEventListener("statechange", evt => {
+ if (worker.state === "activated") {
+ resolve();
+ }
+ });
+ });
+ }
+ );
+
+ const tab = await addJsonViewTab(TEST_JSON_URL);
+
+ ok(
+ tab.linkedBrowser.contentPrincipal.isNullPrincipal,
+ "Should have null principal"
+ );
+
+ is(await countRows(), 3, "There must be three rows");
+
+ const objectCellCount = await getElementCount(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellCount, 1, "There must be one object cell");
+
+ const objectCellText = await getElementText(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellText, "", "The summary is hidden when object is expanded");
+
+ // Clicking the value does not collapse it (so that it can be selected and copied).
+ await clickJsonNode(".jsonPanelBox .treeTable .treeValueCell");
+ is(await countRows(), 3, "There must still be three rows");
+
+ // Clicking the label collapses the auto-expanded node.
+ await clickJsonNode(".jsonPanelBox .treeTable .treeLabel");
+ is(await countRows(), 1, "There must be one row");
+
+ await SpecialPowers.spawn(
+ browser,
+ [{ script: SW, scope: TEST_JSON_URL }],
+ async opts => {
+ const reg = await content.navigator.serviceWorker.getRegistration(
+ opts.scope
+ );
+ await reg.unregister();
+ }
+ );
+
+ BrowserTestUtils.removeTab(swTab);
+});
+
+function countRows() {
+ return getElementCount(".jsonPanelBox .treeTable .treeRow");
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_slash.js b/devtools/client/jsonview/test/browser_jsonview_slash.js
new file mode 100644
index 0000000000..f8abeca7be
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_slash.js
@@ -0,0 +1,16 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ info("Test JSON with slash started.");
+
+ const TEST_JSON_URL = 'data:application/json,{"a/b":[1,2],"a":{"b":[3,4]}}';
+ await addJsonViewTab(TEST_JSON_URL);
+
+ const countBefore = await getElementCount(
+ ".jsonPanelBox .treeTable .treeRow"
+ );
+ is(countBefore, 7, "There must be seven rows");
+});
diff --git a/devtools/client/jsonview/test/browser_jsonview_theme.js b/devtools/client/jsonview/test/browser_jsonview_theme.js
new file mode 100644
index 0000000000..c66d197256
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_theme.js
@@ -0,0 +1,29 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "valid_json.json";
+
+add_task(async function () {
+ info("Test JSON theme started.");
+
+ const oldPref = Services.prefs.getCharPref("devtools.theme");
+ Services.prefs.setCharPref("devtools.theme", "light");
+
+ await addJsonViewTab(TEST_JSON_URL);
+
+ is(await getTheme(), "theme-light", "The initial theme is light");
+
+ Services.prefs.setCharPref("devtools.theme", "dark");
+ is(await getTheme(), "theme-dark", "Theme changed to dark");
+
+ Services.prefs.setCharPref("devtools.theme", "light");
+ is(await getTheme(), "theme-light", "Theme changed to light");
+
+ Services.prefs.setCharPref("devtools.theme", oldPref);
+});
+
+function getTheme() {
+ return getElementAttr(":root", "class");
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_url_linkification.js b/devtools/client/jsonview/test/browser_jsonview_url_linkification.js
new file mode 100644
index 0000000000..19d1f27f0c
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_url_linkification.js
@@ -0,0 +1,88 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ELLIPSIS } = require("resource://devtools/shared/l10n.js");
+
+add_task(async function () {
+ info("Test short URL linkification JSON started");
+
+ const url = "https://example.com/";
+ const tab = await addJsonViewTab(
+ "data:application/json," + JSON.stringify([url])
+ );
+ await testLinkNavigation({ browser: tab.linkedBrowser, url });
+
+ info("Switch back to the JSONViewer");
+ await BrowserTestUtils.switchTab(gBrowser, tab);
+
+ await testLinkNavigation({
+ browser: tab.linkedBrowser,
+ url,
+ clickLabel: true,
+ });
+});
+
+add_task(async function () {
+ info("Test long URL linkification JSON started");
+
+ const url = "https://example.com/" + "a".repeat(100);
+ const tab = await addJsonViewTab(
+ "data:application/json," + JSON.stringify([url])
+ );
+
+ await testLinkNavigation({ browser: tab.linkedBrowser, url });
+
+ info("Switch back to the JSONViewer");
+ await BrowserTestUtils.switchTab(gBrowser, tab);
+
+ await testLinkNavigation({
+ browser: tab.linkedBrowser,
+ url,
+ urlText: url.slice(0, 24) + ELLIPSIS + url.slice(-24),
+ clickLabel: true,
+ });
+});
+
+/**
+ * Assert that the expected link is displayed and that clicking on it navigates to the
+ * expected url.
+ *
+ * @param {Object} option object containing:
+ * - browser (mandatory): the browser the tab will be opened in.
+ * - url (mandatory): The url we should navigate to.
+ * - urlText: The expected displayed text of the url.
+ * Falls back to `url` if not filled
+ * - clickLabel: Should we click the label before doing assertions.
+ */
+async function testLinkNavigation({
+ browser,
+ url,
+ urlText,
+ clickLabel = false,
+}) {
+ const onTabLoaded = BrowserTestUtils.waitForNewTab(gBrowser, url);
+
+ SpecialPowers.spawn(browser, [[urlText || url, url, clickLabel]], args => {
+ const [expectedURLText, expectedURL, shouldClickLabel] = args;
+ const { document } = content;
+
+ if (shouldClickLabel === true) {
+ document.querySelector(".jsonPanelBox .treeTable .treeLabel").click();
+ }
+
+ const link = document.querySelector(
+ ".jsonPanelBox .treeTable .treeValueCell a"
+ );
+ is(link.textContent, expectedURLText, "The expected URL is displayed.");
+ is(link.href, expectedURL, "The URL was linkified.");
+
+ link.click();
+ });
+
+ const newTab = await onTabLoaded;
+ // We only need to check that newTab is truthy since
+ // BrowserTestUtils.waitForNewTab checks the URL.
+ ok(newTab, "The expected tab was opened.");
+}
diff --git a/devtools/client/jsonview/test/browser_jsonview_valid_json.js b/devtools/client/jsonview/test/browser_jsonview_valid_json.js
new file mode 100644
index 0000000000..8ffd1dc1d5
--- /dev/null
+++ b/devtools/client/jsonview/test/browser_jsonview_valid_json.js
@@ -0,0 +1,46 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_JSON_URL = URL_ROOT + "valid_json.json";
+
+add_task(async function () {
+ info("Test valid JSON started");
+
+ const tab = await addJsonViewTab(TEST_JSON_URL);
+
+ ok(
+ tab.linkedBrowser.contentPrincipal.isNullPrincipal,
+ "Should have null principal"
+ );
+
+ is(await countRows(), 3, "There must be three rows");
+
+ const objectCellCount = await getElementCount(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellCount, 1, "There must be one object cell");
+
+ const objectCellText = await getElementText(
+ ".jsonPanelBox .treeTable .objectCell"
+ );
+ is(objectCellText, "", "The summary is hidden when object is expanded");
+
+ // Clicking the value does not collapse it (so that it can be selected and copied).
+ await clickJsonNode(".jsonPanelBox .treeTable .treeValueCell");
+ is(await countRows(), 3, "There must still be three rows");
+
+ // Clicking the label collapses the auto-expanded node.
+ await clickJsonNode(".jsonPanelBox .treeTable .treeLabel");
+ is(await countRows(), 1, "There must be one row");
+
+ // Collapsed nodes are preserved when switching panels.
+ await selectJsonViewContentTab("headers");
+ await selectJsonViewContentTab("json");
+ is(await countRows(), 1, "There must still be one row");
+});
+
+function countRows() {
+ return getElementCount(".jsonPanelBox .treeTable .treeRow");
+}
diff --git a/devtools/client/jsonview/test/chunked_json.sjs b/devtools/client/jsonview/test/chunked_json.sjs
new file mode 100644
index 0000000000..554b62bafd
--- /dev/null
+++ b/devtools/client/jsonview/test/chunked_json.sjs
@@ -0,0 +1,39 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+const key = "json-viewer-chunked-response";
+function setResponse(response) {
+ setObjectState(key, response);
+}
+function getResponse() {
+ let response;
+ getObjectState(key, v => {
+ response = v;
+ });
+ return response;
+}
+
+function handleRequest(request, response) {
+ const { queryString } = request;
+ if (!queryString) {
+ response.processAsync();
+ setResponse(response);
+ response.setHeader("Content-Type", "application/json");
+ // Write something so that the JSON viewer app starts loading.
+ response.write(" ");
+ return;
+ }
+ const [command, value] = queryString.split("=");
+ switch (command) {
+ case "write":
+ getResponse().write(value);
+ break;
+ case "close":
+ getResponse().finish();
+ setResponse(null);
+ break;
+ }
+ response.setHeader("Content-Type", "text/plain");
+ response.write("ok");
+}
diff --git a/devtools/client/jsonview/test/csp_json.json b/devtools/client/jsonview/test/csp_json.json
new file mode 100644
index 0000000000..9fc9368255
--- /dev/null
+++ b/devtools/client/jsonview/test/csp_json.json
@@ -0,0 +1 @@
+{ "csp": true }
diff --git a/devtools/client/jsonview/test/csp_json.json^headers^ b/devtools/client/jsonview/test/csp_json.json^headers^
new file mode 100644
index 0000000000..d6d0a72a4b
--- /dev/null
+++ b/devtools/client/jsonview/test/csp_json.json^headers^
@@ -0,0 +1,2 @@
+Content-Type: application/json
+Content-Security-Policy: default-src 'none'; base-uri 'none';
diff --git a/devtools/client/jsonview/test/empty.html b/devtools/client/jsonview/test/empty.html
new file mode 100644
index 0000000000..c50eddd41f
--- /dev/null
+++ b/devtools/client/jsonview/test/empty.html
@@ -0,0 +1 @@
+<!doctype html>
diff --git a/devtools/client/jsonview/test/head.js b/devtools/client/jsonview/test/head.js
new file mode 100644
index 0000000000..5c9ee85ea2
--- /dev/null
+++ b/devtools/client/jsonview/test/head.js
@@ -0,0 +1,278 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+/* eslint no-unused-vars: [2, {"vars": "local", "args": "none"}] */
+
+"use strict";
+
+// shared-head.js handles imports, constants, and utility functions
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/devtools/client/framework/test/head.js",
+ this
+);
+
+const JSON_VIEW_PREF = "devtools.jsonview.enabled";
+
+// Enable JSON View for the test
+Services.prefs.setBoolPref(JSON_VIEW_PREF, true);
+
+registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(JSON_VIEW_PREF);
+});
+
+// XXX move some API into devtools/shared/test/shared-head.js
+
+/**
+ * Add a new test tab in the browser and load the given url.
+ * @param {String} url
+ * The url to be loaded in the new tab.
+ *
+ * @param {Object} [optional]
+ * An object with the following optional properties:
+ * - appReadyState: The readyState of the JSON Viewer app that you want to
+ * wait for. Its value can be one of:
+ * - "uninitialized": The converter has started the request.
+ * If JavaScript is disabled, there will be no more readyState changes.
+ * - "loading": RequireJS started loading the scripts for the JSON Viewer.
+ * If the load timeouts, there will be no more readyState changes.
+ * - "interactive": The JSON Viewer app loaded, but possibly not all the JSON
+ * data has been received.
+ * - "complete" (default): The app is fully loaded with all the JSON.
+ * - docReadyState: The standard readyState of the document that you want to
+ * wait for. Its value can be one of:
+ * - "loading": The JSON data has not been completely loaded (but the app might).
+ * - "interactive": All the JSON data has been received.
+ * - "complete" (default): Since there aren't sub-resources like images,
+ * behaves as "interactive". Note the app might not be loaded yet.
+ */
+async function addJsonViewTab(
+ url,
+ { appReadyState = "complete", docReadyState = "complete" } = {}
+) {
+ info("Adding a new JSON tab with URL: '" + url + "'");
+ const tabAdded = BrowserTestUtils.waitForNewTab(gBrowser, url);
+ const tabLoaded = addTab(url);
+
+ // The `tabAdded` promise resolves when the JSON Viewer starts loading.
+ // This is usually what we want, however, it never resolves for unrecognized
+ // content types that trigger a download.
+ // On the other hand, `tabLoaded` always resolves, but not until the document
+ // is fully loaded, which is too late if `docReadyState !== "complete"`.
+ // Therefore, we race both promises.
+ const tab = await Promise.race([tabAdded, tabLoaded]);
+ const browser = tab.linkedBrowser;
+
+ const rootDir = getRootDirectory(gTestPath);
+
+ // Catch RequireJS errors (usually timeouts)
+ const error = tabLoaded.then(() =>
+ SpecialPowers.spawn(browser, [], function () {
+ return new Promise((resolve, reject) => {
+ const { requirejs } = content.wrappedJSObject;
+ if (requirejs) {
+ requirejs.onError = err => {
+ info(err);
+ ok(false, "RequireJS error");
+ reject(err);
+ };
+ }
+ });
+ })
+ );
+
+ const data = { rootDir, appReadyState, docReadyState };
+ await Promise.race([
+ error,
+ // eslint-disable-next-line no-shadow
+ ContentTask.spawn(browser, data, async function (data) {
+ // Check if there is a JSONView object.
+ const { JSONView } = content.wrappedJSObject;
+ if (!JSONView) {
+ throw new Error("The JSON Viewer did not load.");
+ }
+
+ const docReadyStates = ["loading", "interactive", "complete"];
+ const docReadyIndex = docReadyStates.indexOf(data.docReadyState);
+ const appReadyStates = ["uninitialized", ...docReadyStates];
+ const appReadyIndex = appReadyStates.indexOf(data.appReadyState);
+ if (docReadyIndex < 0 || appReadyIndex < 0) {
+ throw new Error("Invalid app or doc readyState parameter.");
+ }
+
+ // Wait until the document readyState suffices.
+ const { document } = content;
+ while (docReadyStates.indexOf(document.readyState) < docReadyIndex) {
+ info(
+ `DocReadyState is "${document.readyState}". Await "${data.docReadyState}"`
+ );
+ await new Promise(resolve => {
+ document.addEventListener("readystatechange", resolve, {
+ once: true,
+ });
+ });
+ }
+
+ // Wait until the app readyState suffices.
+ while (appReadyStates.indexOf(JSONView.readyState) < appReadyIndex) {
+ info(
+ `AppReadyState is "${JSONView.readyState}". Await "${data.appReadyState}"`
+ );
+ await new Promise(resolve => {
+ content.addEventListener("AppReadyStateChange", resolve, {
+ once: true,
+ });
+ });
+ }
+ }),
+ ]);
+
+ return tab;
+}
+
+/**
+ * Expanding a node in the JSON tree
+ */
+function clickJsonNode(selector) {
+ info("Expanding node: '" + selector + "'");
+
+ // eslint-disable-next-line no-shadow
+ return ContentTask.spawn(gBrowser.selectedBrowser, selector, selector => {
+ content.document.querySelector(selector).click();
+ });
+}
+
+/**
+ * Select JSON View tab (in the content).
+ */
+function selectJsonViewContentTab(name) {
+ info("Selecting tab: '" + name + "'");
+
+ // eslint-disable-next-line no-shadow
+ return ContentTask.spawn(gBrowser.selectedBrowser, name, async name => {
+ const selector = ".tabs-menu .tabs-menu-item." + CSS.escape(name) + " a";
+ const element = content.document.querySelector(selector);
+ is(element.getAttribute("aria-selected"), "false", "Tab not selected yet");
+ await new Promise(resolve => {
+ content.addEventListener("TabChanged", resolve, { once: true });
+ element.click();
+ });
+ is(element.getAttribute("aria-selected"), "true", "Tab is now selected");
+ });
+}
+
+function getElementCount(selector) {
+ info("Get element count: '" + selector + "'");
+
+ return SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [selector],
+ selectorChild => {
+ return content.document.querySelectorAll(selectorChild).length;
+ }
+ );
+}
+
+function getElementText(selector) {
+ info("Get element text: '" + selector + "'");
+
+ return SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [selector],
+ selectorChild => {
+ const element = content.document.querySelector(selectorChild);
+ return element ? element.textContent : null;
+ }
+ );
+}
+
+function getElementAttr(selector, attr) {
+ info("Get attribute '" + attr + "' for element '" + selector + "'");
+
+ return SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [selector, attr],
+ (selectorChild, attrChild) => {
+ const element = content.document.querySelector(selectorChild);
+ return element ? element.getAttribute(attrChild) : null;
+ }
+ );
+}
+
+function focusElement(selector) {
+ info("Focus element: '" + selector + "'");
+
+ return SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [selector],
+ selectorChild => {
+ const element = content.document.querySelector(selectorChild);
+ if (element) {
+ element.focus();
+ }
+ }
+ );
+}
+
+/**
+ * Send the string aStr to the focused element.
+ *
+ * For now this method only works for ASCII characters and emulates the shift
+ * key state on US keyboard layout.
+ */
+function sendString(str, selector) {
+ info("Send string: '" + str + "'");
+
+ return SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [selector, str],
+ (selectorChild, strChild) => {
+ if (selectorChild) {
+ const element = content.document.querySelector(selectorChild);
+ if (element) {
+ element.focus();
+ }
+ }
+
+ EventUtils.sendString(strChild, content);
+ }
+ );
+}
+
+function waitForTime(delay) {
+ return new Promise(resolve => setTimeout(resolve, delay));
+}
+
+function waitForFilter() {
+ return SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {
+ return new Promise(resolve => {
+ const firstRow = content.document.querySelector(
+ ".jsonPanelBox .treeTable .treeRow"
+ );
+
+ // Check if the filter is already set.
+ if (firstRow.classList.contains("hidden")) {
+ resolve();
+ return;
+ }
+
+ // Wait till the first row has 'hidden' class set.
+ const observer = new content.MutationObserver(function (mutations) {
+ for (let i = 0; i < mutations.length; i++) {
+ const mutation = mutations[i];
+ if (mutation.attributeName == "class") {
+ if (firstRow.classList.contains("hidden")) {
+ observer.disconnect();
+ resolve();
+ break;
+ }
+ }
+ }
+ });
+
+ observer.observe(firstRow, { attributes: true });
+ });
+ });
+}
+
+function normalizeNewLines(value) {
+ return value.replace("(\r\n|\n)", "\n");
+}
diff --git a/devtools/client/jsonview/test/invalid_json.json b/devtools/client/jsonview/test/invalid_json.json
new file mode 100644
index 0000000000..004e1e2032
--- /dev/null
+++ b/devtools/client/jsonview/test/invalid_json.json
@@ -0,0 +1 @@
+{,}
diff --git a/devtools/client/jsonview/test/invalid_json.json^headers^ b/devtools/client/jsonview/test/invalid_json.json^headers^
new file mode 100644
index 0000000000..6010bfd188
--- /dev/null
+++ b/devtools/client/jsonview/test/invalid_json.json^headers^
@@ -0,0 +1 @@
+Content-Type: application/json; charset=utf-8
diff --git a/devtools/client/jsonview/test/manifest_json.json b/devtools/client/jsonview/test/manifest_json.json
new file mode 100644
index 0000000000..b178f7acf4
--- /dev/null
+++ b/devtools/client/jsonview/test/manifest_json.json
@@ -0,0 +1,49 @@
+{
+ "name": "HackerWeb",
+ "short_name": "HackerWeb",
+ "start_url": ".",
+ "display": "standalone",
+ "background_color": "#fff",
+ "description": "A simply readable Hacker News app.",
+ "icons": [
+ {
+ "src": "images/touch/homescreen48.png",
+ "sizes": "48x48",
+ "type": "image/png"
+ },
+ {
+ "src": "images/touch/homescreen72.png",
+ "sizes": "72x72",
+ "type": "image/png"
+ },
+ {
+ "src": "images/touch/homescreen96.png",
+ "sizes": "96x96",
+ "type": "image/png"
+ },
+ {
+ "src": "images/touch/homescreen144.png",
+ "sizes": "144x144",
+ "type": "image/png"
+ },
+ {
+ "src": "images/touch/homescreen168.png",
+ "sizes": "168x168",
+ "type": "image/png"
+ },
+ {
+ "src": "images/touch/homescreen192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ }
+ ],
+ "related_applications": [
+ {
+ "platform": "web"
+ },
+ {
+ "platform": "play",
+ "url": "https://play.google.com/store/apps/details?id=cheeaun.hackerweb"
+ }
+ ]
+}
diff --git a/devtools/client/jsonview/test/manifest_json.json^headers^ b/devtools/client/jsonview/test/manifest_json.json^headers^
new file mode 100644
index 0000000000..2bab061d43
--- /dev/null
+++ b/devtools/client/jsonview/test/manifest_json.json^headers^
@@ -0,0 +1 @@
+Content-Type: application/manifest+json; charset=utf-8
diff --git a/devtools/client/jsonview/test/passthrough-sw.js b/devtools/client/jsonview/test/passthrough-sw.js
new file mode 100644
index 0000000000..019d218bc2
--- /dev/null
+++ b/devtools/client/jsonview/test/passthrough-sw.js
@@ -0,0 +1,5 @@
+"use strict";
+
+addEventListener("fetch", evt => {
+ evt.respondWith(fetch(evt.request));
+});
diff --git a/devtools/client/jsonview/test/simple_json.json b/devtools/client/jsonview/test/simple_json.json
new file mode 100644
index 0000000000..d1544242f5
--- /dev/null
+++ b/devtools/client/jsonview/test/simple_json.json
@@ -0,0 +1 @@
+{ "name": "value" }
diff --git a/devtools/client/jsonview/test/simple_json.json^headers^ b/devtools/client/jsonview/test/simple_json.json^headers^
new file mode 100644
index 0000000000..6010bfd188
--- /dev/null
+++ b/devtools/client/jsonview/test/simple_json.json^headers^
@@ -0,0 +1 @@
+Content-Type: application/json; charset=utf-8
diff --git a/devtools/client/jsonview/test/valid_json.json b/devtools/client/jsonview/test/valid_json.json
new file mode 100644
index 0000000000..ca7356ccdb
--- /dev/null
+++ b/devtools/client/jsonview/test/valid_json.json
@@ -0,0 +1,6 @@
+{
+ "family": {
+ "father": "John Doe",
+ "mother": "Alice Doe"
+ }
+}
diff --git a/devtools/client/jsonview/test/valid_json.json^headers^ b/devtools/client/jsonview/test/valid_json.json^headers^
new file mode 100644
index 0000000000..6010bfd188
--- /dev/null
+++ b/devtools/client/jsonview/test/valid_json.json^headers^
@@ -0,0 +1 @@
+Content-Type: application/json; charset=utf-8
diff --git a/devtools/client/jsonview/viewer-config.js b/devtools/client/jsonview/viewer-config.js
new file mode 100644
index 0000000000..6ab0de0a8f
--- /dev/null
+++ b/devtools/client/jsonview/viewer-config.js
@@ -0,0 +1,46 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* global requirejs */
+
+"use strict";
+
+// Send readyState change notification event to the window. It's useful for tests.
+JSONView.readyState = "loading";
+window.dispatchEvent(new CustomEvent("AppReadyStateChange"));
+
+// Services is required in the Reps bundle but can't be loaded in the json-viewer.
+// Since it's only used for the ObjectInspector, that the json-viewer does not use, we
+// can mock it. The mock should be removed when we un-bundle reps, (i.e. land individual
+// files instead of a big bundle).
+define("ServicesMock", () => ({ appinfo: {} }));
+// custom-formatter is required in the Reps bundle but 1. we don't need in the JSON Viewer,
+// and 2. it causes issues as this requires the ObjectInspector, which can't be loaded
+// via requirejs.
+define("CustomFormatterMock", () => ({}));
+
+/**
+ * RequireJS configuration for JSON Viewer.
+ *
+ * React module ID is using exactly the same (relative) path as the rest
+ * of the code base, so it's consistent and modules can be easily reused.
+ */
+require.config({
+ baseUrl: "resource://devtools-client-jsonview/",
+ paths: {
+ "devtools/client/jsonview": "resource://devtools-client-jsonview",
+ "devtools/client/shared": "resource://devtools-client-shared",
+ "devtools/shared": "resource://devtools/shared",
+ Services: "resource://devtools-client-shared/vendor/react-prop-types",
+ },
+ map: {
+ "*": {
+ Services: "ServicesMock",
+ "devtools/client/shared/components/reps/reps/custom-formatter":
+ "CustomFormatterMock",
+ },
+ },
+});
+
+// Load the main panel module
+requirejs(["json-viewer"]);