Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change vlq encoding to encode only positive ints #389

Merged
merged 1 commit into from
Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion __snapshots__/PuppeteerReplayStringifyExtension.test.ts.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,6 @@ export async function run(extension) {
if (process && import.meta.url === url.pathToFileURL(process.argv[1]).href) {
run()
}
//# recorderSourceMap=CQc
//# recorderSourceMap=BIO

`;
2 changes: 1 addition & 1 deletion __snapshots__/lighthouse.test.ts.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,6 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CaIiBMuBaoCYgDiB
//# recorderSourceMap=BNERGXNkBMwBR

`;
20 changes: 10 additions & 10 deletions __snapshots__/stringify.test.ts.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQI
//# recorderSourceMap=BIE

`;

Expand Down Expand Up @@ -415,7 +415,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQS
//# recorderSourceMap=BIJ

`;

Expand Down Expand Up @@ -633,7 +633,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQa
//# recorderSourceMap=BIN

`;

Expand Down Expand Up @@ -850,7 +850,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQc
//# recorderSourceMap=BIO

`;

Expand Down Expand Up @@ -1069,7 +1069,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQc
//# recorderSourceMap=BIO

`;

Expand Down Expand Up @@ -1276,7 +1276,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQI
//# recorderSourceMap=BIE

`;

Expand Down Expand Up @@ -1483,7 +1483,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQI
//# recorderSourceMap=BIE

`;

Expand Down Expand Up @@ -1696,7 +1696,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQMcI
//# recorderSourceMap=BIGOE

`;

Expand Down Expand Up @@ -1905,7 +1905,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQI
//# recorderSourceMap=BIE

`;

Expand Down Expand Up @@ -2114,7 +2114,7 @@ const puppeteer = require('puppeteer'); // v13.0.0 or later
console.error(err);
process.exit(1);
});
//# recorderSourceMap=CQI
//# recorderSourceMap=BIE

`;

Expand Down
11 changes: 0 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@
"dependencies": {
"cli-table3": "0.6.3",
"colorette": "2.0.19",
"vlq": "2.0.4",
"yargs": "17.6.1"
}
}
4 changes: 0 additions & 4 deletions src/@types/vlq/index.d.ts

This file was deleted.

8 changes: 4 additions & 4 deletions src/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { LineWriter } from './LineWriter.js';
import { PuppeteerStringifyExtension } from './PuppeteerStringifyExtension.js';
import type { Step, UserFlow } from './Schema.js';
import { StringifyExtension } from './StringifyExtension.js';
import * as vlq from 'vlq';
import { decode, encode } from './vlq.js';

export interface StringifyOptions {
extension?: StringifyExtension;
Expand Down Expand Up @@ -54,7 +54,7 @@ export async function stringify(

await ext.beforeAllSteps?.(out, flow);

const sourceMap: Array<number> = [1];
const sourceMap: Array<number> = [1]; // The first int indicates the version.
for (const step of flow.steps) {
const firstLine = out.getSize();
await ext.beforeEachStep?.(out, step, flow);
Expand All @@ -65,7 +65,7 @@ export async function stringify(
}
await ext.afterAllSteps?.(out, flow);

out.appendLine(SOURCE_MAP_PREFIX + vlq.encode(sourceMap));
out.appendLine(SOURCE_MAP_PREFIX + encode(sourceMap));

return out.toString();
}
Expand Down Expand Up @@ -107,7 +107,7 @@ export function parseSourceMap(text: string): SourceMap | undefined {
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i] as string;
if (line.trim().startsWith(SOURCE_MAP_PREFIX)) {
return vlq.decode(line.trim().substring(SOURCE_MAP_PREFIX.length));
return decode(line.trim().substring(SOURCE_MAP_PREFIX.length));
}
}
return;
Expand Down
82 changes: 82 additions & 0 deletions src/vlq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const alpha =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

const charToIdx = alpha.split('').reduce((acc, char, idx) => {
acc.set(char, idx);
return acc;
}, new Map());

const LEAST_5_BIT_MASK = 0b011111;
const CONTINUATION_BIT_MASK = 0b100000;
const MAX_INT = 2147483647;

/**
* Encoding variable length integer into base64 (6-bit):
*
* 1 N N N N N | 0 N N N N N
*
* The first bit indicates if there is more data for the int.
*/
export function encodeInt(num: number) {
if (num < 0) {
throw new Error('Only postive integers and zero are supported');
}
if (num > MAX_INT) {
throw new Error(
'Only integers between 0 and ' + MAX_INT + ' are supported'
);
}
const result = [];
do {
let payload = num & LEAST_5_BIT_MASK;
num >>>= 5;
if (num > 0) payload |= CONTINUATION_BIT_MASK;
result.push(alpha[payload]);
} while (num !== 0);
return result.join('');
}

export function encode(nums: number[]): string {
const parts = [];
for (const num of nums) {
parts.push(encodeInt(num));
}
return parts.join('');
}

export function decode(str: string) {
const results = [];
const chrs = str.split('');

let result = 0;
let shift = 0;
for (const ch of chrs) {
const num = charToIdx.get(ch);
result |= (num & LEAST_5_BIT_MASK) << shift;
shift += 5;
const hasMore = num & CONTINUATION_BIT_MASK;
if (!hasMore) {
results.push(result);
result = 0;
shift = 0;
}
}

return results;
}
8 changes: 4 additions & 4 deletions test/stringify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { StringifyExtension } from '../src/StringifyExtension.js';
import { Step, StepType, UserFlow } from '../src/Schema.js';
import { LineWriter } from '../src/LineWriter.js';
import snapshot from 'snap-shot-it';
import * as vlq from 'vlq';
import { decode } from '../src/vlq.js';

describe('stringify', () => {
it('should print the correct script for a navigate step', async () => {
Expand Down Expand Up @@ -250,7 +250,7 @@ describe('stringify', () => {
'stringifyStep0',
'afterStep0',
'afterAll',
'//# recorderSourceMap=CCG',
'//# recorderSourceMap=BBD',
'',
].join('\n')
);
Expand All @@ -272,7 +272,7 @@ describe('stringify', () => {
.reverse()
.find((line) => line.trim() !== '');
snapshot(
vlq.decode(sourceMapLine?.split('//# recorderSourceMap=').pop() as string)
decode(sourceMapLine?.split('//# recorderSourceMap=').pop() as string)
);
});

Expand All @@ -281,7 +281,7 @@ describe('stringify', () => {
test
test
test
//# recorderSourceMap=CCG
//# recorderSourceMap=BBD
`);
assert.deepStrictEqual(sourceMap, [1, 1, 3]);
});
Expand Down
41 changes: 41 additions & 0 deletions test/vlq.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { encodeInt, decode, encode } from '../src/vlq.js';
import { assert } from 'chai';

describe('vlq', () => {
it('should encode', () => {
assert.strictEqual(encodeInt(0), 'A');
assert.strictEqual(encodeInt(1), 'B');
assert.strictEqual(encodeInt(123), '7D');
assert.strictEqual(encodeInt(123) + encodeInt(123456789), '7D1oz31D');
assert.strictEqual(encodeInt(123456789), '1oz31D');
assert.strictEqual(encodeInt(2147483647), '//////B');
});
it('should decode', () => {
assert.deepStrictEqual(decode('A'), [0]);
assert.deepStrictEqual(decode('C'), [2]);
assert.deepStrictEqual(decode('D'), [3]);
assert.deepStrictEqual(decode('7D'), [123]);
assert.deepStrictEqual(decode('1oz31D'), [123456789]);
assert.deepStrictEqual(decode('7D1oz31D'), [123, 123456789]);
assert.deepStrictEqual(decode('//////B'), [2147483647]);
});
it('should encode array', () => {
assert.strictEqual(encode([0, 1, 123]), 'AB7D');
});
});
3 changes: 1 addition & 2 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"strictNullChecks": true,
"strictPropertyInitialization": true,
"target": "ES2019",
"useUnknownInCatchVariables": true,
"typeRoots": ["./node_modules/@types", "./src/@types"]
"useUnknownInCatchVariables": true
}
}