insomnia-plugin-jsonc 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Guillaume Ongenae
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,16 +1,77 @@
1
1
  # insomnia-plugin-jsonc
2
2
 
3
- Strip JSON comments from your request body.
3
+ Write comments and trailing commas in your JSON request bodies. They are stripped before the request is sent.
4
+
5
+ - **The original**: published on npm in January 2022, before the other JSON comments plugins for Insomnia.
6
+ - **The fastest**: 3 to 10 times faster than [`strip-json-comments`](https://github.com/sindresorhus/strip-json-comments), and up to 20 times faster on large bodies than the regular expression other plugins use. See [`bench/`](bench/README.md).
7
+ - **Unbreakable**: handles the cases other implementations get wrong, such as a string ending with an escaped backslash (`"C:\\dir\\"`) or a line comment ended by a lone `\r`. Strings are never altered, empty and malformed bodies never make it throw, and the body is scanned in linear time, even on malformed input. No runtime dependencies, no network access.
8
+
9
+ ## Example
10
+
11
+ What you write in Insomnia:
12
+
13
+ <!-- prettier-ignore -->
14
+ ```jsonc
15
+ {
16
+ "page": 1, // current page
17
+ /* "debug": true, */
18
+ "url": "https://example.com", // `//` inside strings is kept
19
+ "tags": ["a", "b",],
20
+ }
21
+ ```
22
+
23
+ What the server receives:
24
+
25
+ ```json
26
+ {
27
+ "page": 1,
28
+
29
+ "url": "https://example.com",
30
+ "tags": ["a", "b"]
31
+ }
32
+ ```
4
33
 
5
34
  ## Installation
6
35
 
7
- - Open Insomnia options (Ctrl + , | Cmd + ,)
8
- - Type `insomnia-plugin-jsonc` on the Plugins tab
36
+ ### Plugin Hub
37
+
38
+ Install from the [Insomnia Plugin Hub](https://insomnia.rest/plugins/insomnia-plugin-jsonc).
39
+
40
+ ### From Insomnia
41
+
42
+ 1. Open Preferences (Ctrl + , | Cmd + ,)
43
+ 2. Go to the Plugins tab
44
+ 3. Enter `insomnia-plugin-jsonc` and click Install Plugin
45
+
46
+ ### Manually
47
+
48
+ Copy this folder into the Insomnia plugins directory:
49
+
50
+ - Windows: `%APPDATA%\Insomnia\plugins\`
51
+ - macOS: `~/Library/Application Support/Insomnia/plugins/`
52
+ - Linux: `~/.config/Insomnia/plugins/`
53
+
54
+ ## What is stripped
55
+
56
+ - Line comments: `// ...` up to the end of the line
57
+ - Block comments: `/* ... */`, which can span several lines
58
+ - Trailing commas before `]` or `}`, even with a comment in between
59
+
60
+ Content inside strings is never touched, so `"https://example.com"` or `"a /* b */"` stay as they are.
61
+
62
+ The plugin only applies to JSON bodies: `application/json`, with or without parameters (`application/json; charset=utf-8`), and `+json` types (`application/vnd.api+json`). Other bodies are sent unchanged.
63
+
64
+ ## Limitations
65
+
66
+ - Whitespace around a removed comment is kept, so the sent body may contain extra spaces or blank lines.
67
+ - The result is not validated: invalid JSON is sent as is, and the server reports the error.
68
+
69
+ ## How it works
9
70
 
10
- ## Usage
71
+ A request hook scans the body once, character by character, jumping over strings and comments. It removes comments and trailing commas, and copies the rest as is: the body is not parsed and serialized again, so its formatting is preserved. A body with nothing to strip is returned untouched.
11
72
 
12
- Just write valid JavaScript comments in JSON body request and send your request without minding them.
73
+ See [`bench/`](bench/README.md) for a comparison with a regular expression, another scanner and [`strip-json-comments`](https://github.com/sindresorhus/strip-json-comments).
13
74
 
14
- ## Deps
75
+ ## License
15
76
 
16
- Use [`json-easy-strip`](https://www.npmjs.com/package/json-easy-strip)'s RegExp to strip comments.
77
+ MIT
package/cover.svg ADDED
@@ -0,0 +1,28 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 400" width="1200" height="400">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#4000BF"/>
5
+ <stop offset="1" stop-color="#2A0080"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect width="1200" height="400" fill="url(#bg)"/>
9
+ <!-- { } logo -->
10
+ <g transform="translate(80 72) scale(0.5)">
11
+ <g fill="none" stroke="#FFFFFF" stroke-width="32" stroke-linecap="round" stroke-linejoin="round">
12
+ <path d="M176 112h-16c-24 0-40 16-40 40v56c0 24-16 48-40 48 24 0 40 24 40 48v56c0 24 16 40 40 40h16"/>
13
+ <path d="M336 112h16c24 0 40 16 40 40v56c0 24 16 48 40 48-24 0-40 24-40 48v56c0 24-16 40-40 40h-16"/>
14
+ </g>
15
+ <g stroke="#B794FF" stroke-width="28" stroke-linecap="round">
16
+ <path d="M196 312l40-112"/>
17
+ <path d="M276 312l40-112"/>
18
+ </g>
19
+ </g>
20
+ <g font-family="Menlo, Consolas, 'DejaVu Sans Mono', monospace">
21
+ <text x="400" y="190" font-size="64" font-weight="bold" fill="#FFFFFF">JSON Comments</text>
22
+ <text x="400" y="250" font-size="30" fill="#D9C7FF">Strips comments from JSON request bodies.</text>
23
+ <!-- before → after -->
24
+ <text x="400" y="318" font-size="24" fill="#FFFFFF">{"a": 1<tspan fill="#B794FF" text-decoration="line-through">, /* note */</tspan>}</text>
25
+ <text x="720" y="318" font-size="24" fill="#B794FF">→</text>
26
+ <text x="770" y="318" font-size="24" fill="#FFFFFF">{"a": 1}</text>
27
+ </g>
28
+ </svg>
package/icon.svg ADDED
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
2
+ <rect width="512" height="512" rx="96" fill="#4000BF"/>
3
+ <!-- { } -->
4
+ <g fill="none" stroke="#FFFFFF" stroke-width="32" stroke-linecap="round" stroke-linejoin="round">
5
+ <path d="M176 112h-16c-24 0-40 16-40 40v56c0 24-16 48-40 48 24 0 40 24 40 48v56c0 24 16 40 40 40h16"/>
6
+ <path d="M336 112h16c24 0 40 16 40 40v56c0 24 16 48 40 48-24 0-40 24-40 48v56c0 24-16 40-40 40h-16"/>
7
+ </g>
8
+ <!-- // -->
9
+ <g stroke="#B794FF" stroke-width="28" stroke-linecap="round">
10
+ <path d="M196 312l40-112"/>
11
+ <path d="M276 312l40-112"/>
12
+ </g>
13
+ </svg>
package/main.js CHANGED
@@ -1,34 +1,38 @@
1
+ const { stripJSONC } = require("./strip");
2
+
1
3
  /**
2
4
  * JSON Content-Type
3
5
  */
4
6
  const CONTENT_TYPE_JSON = "application/json";
5
7
 
6
8
  /**
7
- * Strip comments from a JSON string
8
- *
9
- * Taken from [`json-easy-strip`](https://www.npmjs.com/package/json-easy-strip).
9
+ * Check if a MIME type is JSON, ignoring its parameters
10
10
  *
11
- * Extracted to not parse and stringify again the JSON string
11
+ * Matches `application/json` and structured syntax suffixes like `application/vnd.api+json`.
12
12
  *
13
- * @param data the JSON string with comments
14
- * @returns the JSON string without comments
13
+ * @param mimeType the MIME type, possibly with parameters (`application/json; charset=utf-8`)
14
+ * @returns whether the MIME type is JSON
15
15
  */
16
- const stripJSONComments = (data) =>
17
- data.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) =>
18
- g ? "" : m
19
- );
16
+ const isJSONMimeType = (mimeType) => {
17
+ const type = String(mimeType ?? "")
18
+ .split(";")[0]
19
+ .trim()
20
+ .toLowerCase();
21
+ return type === CONTENT_TYPE_JSON || type.endsWith("+json");
22
+ };
20
23
 
21
24
  /**
22
- * Hook to update request body and remove comments
25
+ * Hook to update request body and remove comments and trailing commas
23
26
  * @param context insomnia request context
24
27
  * @link https://docs.insomnia.rest/insomnia/context-object-reference
25
28
  */
26
29
  const updateRequestBodyHook = (context) => {
27
30
  const body = context.request.getBody();
28
- if (body.mimeType === CONTENT_TYPE_JSON) {
31
+ // `text` is undefined on an empty body
32
+ if (isJSONMimeType(body.mimeType) && typeof body.text === "string") {
29
33
  context.request.setBody({
30
34
  ...body,
31
- text: stripJSONComments(body.text),
35
+ text: stripJSONC(body.text),
32
36
  });
33
37
  }
34
38
  };
package/package.json CHANGED
@@ -1,12 +1,22 @@
1
1
  {
2
2
  "name": "insomnia-plugin-jsonc",
3
- "version": "0.1.0",
4
- "description": "Insomnia plugin to use comments in JSON body",
3
+ "version": "0.2.1",
4
+ "description": "Write // and /* */ comments in JSON request bodies in Insomnia",
5
5
  "main": "main.js",
6
+ "files": [
7
+ "main.js",
8
+ "strip.js",
9
+ "icon.svg",
10
+ "cover.svg"
11
+ ],
6
12
  "insomnia": {
7
13
  "name": "jsonc",
8
- "displayName": "JSON Comments Plugin",
9
- "description": "Plugin to use comments in JSON body.",
14
+ "displayName": "JSON Comments & Trailing Commas",
15
+ "description": "Strips comments from JSON request bodies.",
16
+ "images": {
17
+ "icon": "icon.svg",
18
+ "cover": "cover.svg"
19
+ },
10
20
  "publisher": {
11
21
  "name": "Guillaume Ongenae",
12
22
  "icon": "https://avatars.githubusercontent.com/u/9453090"
@@ -14,11 +24,14 @@
14
24
  "unlisted": false
15
25
  },
16
26
  "scripts": {
17
- "test": "node test.js"
27
+ "test": "node --test test.js",
28
+ "prepublishOnly": "npm test",
29
+ "format": "npx prettier@3 --write .",
30
+ "bench": "node --expose-gc bench/bench.js"
18
31
  },
19
32
  "repository": {
20
33
  "type": "git",
21
- "url": "git+ssh://git@github.com/algoan/insomnia-plugin-jsonc.git"
34
+ "url": "git+ssh://git@github.com/g-ongenae/insomnia-plugin-jsonc.git"
22
35
  },
23
36
  "keywords": [
24
37
  "insomnia",
@@ -33,6 +46,8 @@
33
46
  "url": "https://github.com/g-ongenae/insomnia-plugin-jsonc/issues"
34
47
  },
35
48
  "homepage": "https://github.com/g-ongenae/insomnia-plugin-jsonc#readme",
36
- "dependencies": {},
37
- "devDependencies": {}
49
+ "devDependencies": {
50
+ "fast-check": "^4.10.2",
51
+ "strip-json-comments": "^5.0.3"
52
+ }
38
53
  }
package/strip.js ADDED
@@ -0,0 +1,150 @@
1
+ const QUOTE = 34; // "
2
+ const SLASH = 47; // /
3
+ const STAR = 42; // *
4
+ const BACKSLASH = 92; // \
5
+ const COMMA = 44; // ,
6
+ const CLOSING_BRACKET = 93; // ]
7
+ const CLOSING_BRACE = 125; // }
8
+
9
+ /**
10
+ * Check if a character code is JSON whitespace
11
+ * @param code the character code
12
+ * @returns whether it is a space, a tab, a line feed or a carriage return
13
+ */
14
+ const isWhitespace = (code) =>
15
+ code === 32 || code === 10 || code === 13 || code === 9;
16
+
17
+ /**
18
+ * Check if a character code ends a line comment
19
+ *
20
+ * Same line terminators as JavaScript, which `.` does not match in the previous regex.
21
+ *
22
+ * @param code the character code
23
+ * @returns whether it is `\n`, `\r`, `\u2028` or `\u2029`
24
+ */
25
+ const isLineTerminator = (code) =>
26
+ code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
27
+
28
+ /**
29
+ * Find the end of the line comment opening at `start`
30
+ *
31
+ * The line terminator is kept, so that the line structure is preserved.
32
+ *
33
+ * @param data the JSONC string
34
+ * @param start the index of the comment's first slash
35
+ * @returns the index of the line terminator, or the length of the string
36
+ */
37
+ const skipLineComment = (data, start) => {
38
+ let i = start + 2;
39
+ while (i < data.length && !isLineTerminator(data.charCodeAt(i))) i++;
40
+ return i;
41
+ };
42
+
43
+ /**
44
+ * Find the end of the string opening at `start`
45
+ *
46
+ * A quote preceded by an odd number of backslashes is escaped, so `"C:\\"` ends on its last quote.
47
+ *
48
+ * @param data the JSONC string
49
+ * @param start the index of the opening quote
50
+ * @returns the index after the closing quote, or -1 if the string is not terminated
51
+ */
52
+ const skipString = (data, start) => {
53
+ let i = start;
54
+ for (;;) {
55
+ const quote = data.indexOf('"', i + 1);
56
+ if (quote === -1) return -1;
57
+ let backslash = quote - 1;
58
+ while (data.charCodeAt(backslash) === BACKSLASH) backslash--;
59
+ if ((quote - 1 - backslash) % 2 === 0) return quote + 1;
60
+ i = quote;
61
+ }
62
+ };
63
+
64
+ /**
65
+ * Strip comments and trailing commas from a JSONC string
66
+ *
67
+ * Scans the string once, jumping over strings and comments with `indexOf`, and copies
68
+ * the kept text by slices. The string is returned as is when nothing is removed.
69
+ *
70
+ * An unterminated block comment is kept, so that invalid JSON is sent as is.
71
+ *
72
+ * @param data the JSONC string
73
+ * @returns the JSON string
74
+ */
75
+ const stripJSONC = (data) => {
76
+ const length = data.length;
77
+ /** Kept slices, only allocated once something is removed */
78
+ let parts = null;
79
+ /** First index not copied to `parts` yet */
80
+ let start = 0;
81
+ /** Index of a comma only followed by whitespace or comments so far */
82
+ let comma = -1;
83
+ /** Index in `parts` of that comma, once copied */
84
+ let commaPart = -1;
85
+ /** Whether a block comment can still be closed, to not search the rest again for each opening */
86
+ let hasBlockEnd = true;
87
+
88
+ const flush = (end) => {
89
+ parts ??= [];
90
+ if (end > start) parts.push(data.slice(start, end));
91
+ };
92
+
93
+ // Copy a pending comma in its own part, to be able to drop it on a closing bracket
94
+ const detachComma = () => {
95
+ if (comma === -1 || commaPart !== -1) return;
96
+ flush(comma);
97
+ commaPart = parts.push(",") - 1;
98
+ start = comma + 1;
99
+ };
100
+
101
+ for (let i = 0; i < length;) {
102
+ const code = data.charCodeAt(i);
103
+ if (code === QUOTE) {
104
+ const end = skipString(data, i);
105
+ if (end === -1) break;
106
+ comma = -1;
107
+ i = end;
108
+ } else if (code === SLASH && data.charCodeAt(i + 1) === SLASH) {
109
+ detachComma();
110
+ flush(i);
111
+ i = start = skipLineComment(data, i);
112
+ } else if (
113
+ code === SLASH &&
114
+ data.charCodeAt(i + 1) === STAR &&
115
+ hasBlockEnd
116
+ ) {
117
+ const end = data.indexOf("*/", i + 2);
118
+ if (end === -1) {
119
+ // No later block comment can be terminated either
120
+ hasBlockEnd = false;
121
+ continue;
122
+ }
123
+ detachComma();
124
+ flush(i);
125
+ i = start = end + 2;
126
+ } else if (code === COMMA) {
127
+ comma = i;
128
+ commaPart = -1;
129
+ i++;
130
+ } else if (code === CLOSING_BRACKET || code === CLOSING_BRACE) {
131
+ if (comma !== -1 && commaPart !== -1) {
132
+ parts[commaPart] = "";
133
+ } else if (comma !== -1) {
134
+ flush(comma);
135
+ start = comma + 1;
136
+ }
137
+ comma = -1;
138
+ i++;
139
+ } else {
140
+ if (!isWhitespace(code)) comma = -1;
141
+ i++;
142
+ }
143
+ }
144
+
145
+ if (parts === null) return data;
146
+ flush(length);
147
+ return parts.join("");
148
+ };
149
+
150
+ module.exports = { stripJSONC };
package/test.js DELETED
@@ -1,44 +0,0 @@
1
- const { requestHooks } = require('./main');
2
-
3
- /**
4
- * Create a fake insomnia context with a validation on the setBody
5
- * @param {object} givenBody
6
- * @param {object} expectedBody
7
- * @returns a fake insomnia context with a validation
8
- */
9
- const fakeContext = (id, givenBody, expectedBody) => {
10
- return {
11
- request: {
12
- getBody: () => givenBody,
13
- setBody: (actualBody) => {
14
- const result = actualBody.text === expectedBody.text
15
- ? `${id} | passed`
16
- : `${id} | expected: '${expectedBody.text}' => received: '${actualBody.text}'`;
17
-
18
- console.log(result);
19
- },
20
- }
21
- };
22
- };
23
-
24
- /**
25
- * List of test cases
26
- */
27
- const cases = [
28
- // Should not alter non JSON body
29
- [{ mimeType: 'non-json', text: 'foo' }, { mimeType: 'non-json', text: 'foo' }],
30
- // Should not alter JSON body without comments
31
- [{ mimeType: 'application/json', text: 'foo' }, { mimeType: 'application/json', text: 'foo' }],
32
- [{ mimeType: 'application/json', text: '{"foo": "bar"}' }, { mimeType: 'application/json', text: '{"foo": "bar"}' }],
33
- // Should remove comments from JSON body (space are preserved)
34
- [{ mimeType: 'application/json', text: '{"foo": /* hello */ "bar"}' }, { mimeType: 'application/json', text: '{"foo": "bar"}' }],
35
- [{ mimeType: 'application/json', text: '/* hello */ {"foo": "bar"}' }, { mimeType: 'application/json', text: ' {"foo": "bar"}' }],
36
- [{ mimeType: 'application/json', text: '{"foo": "bar" // hello\n }' }, { mimeType: 'application/json', text: '{"foo": "bar" \n }' }],
37
- ];
38
-
39
- /**
40
- * Call and test the hook
41
- */
42
- for (const [index, test] of Object.entries(cases)) {
43
- requestHooks[0](fakeContext(index, ...test));
44
- }