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

add webpack bundle injection and unit tests to build-plugins #871

Merged
merged 4 commits into from
Oct 18, 2024
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
522 changes: 468 additions & 54 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions packages/build-plugins/.mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extension": ["ts"],
"spec": "test/**/*.test.ts",
"require": "ts-node/register"
}
7 changes: 7 additions & 0 deletions packages/build-plugins/.nycrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"check-coverage": true,
"branch": 80,
"lines": 80,
"functions": 80,
"statements": 80
}
15 changes: 15 additions & 0 deletions packages/build-plugins/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
# Splunk Web Build Plugins

> :construction: This project is currently **UNDER DEVELOPMENT**.

## Usage

```js
// webpack.config.js

const { ollyWebWebpackPlugin } = require('@splunk/olly-web-build-plugins');

module.exports = {
/* ... */
plugins: [
ollyWebWebpackPlugin({ /* options */ })
]
}
```
17 changes: 16 additions & 1 deletion packages/build-plugins/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"repository": "github:signalfx/splunk-otel-js-browser",
"scripts": {
"compile": "npm-run-all -s compile:*",
"compile:tsc": "tsc --build tsconfig.cjs.json tsconfig.esm.json"
"compile:tsc": "tsc --build tsconfig.cjs.json tsconfig.esm.json",
"test:unit:ci": "env TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT=tsconfig.cjs.json nyc mocha"
},
"author": "Splunk Observability Instrumentals Team <[email protected]>",
"license": "Apache-2.0",
Expand All @@ -26,6 +27,20 @@
"dist/esm/**/*.js.map",
"dist/esm/**/*.d.ts"
],
"dependencies": {
"unplugin": "^1.14.1"
},
"devDependencies": {
"@types/chai": "^4.3.5",
"@types/mocha": "^10.0.1",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"nyc": "^15.1.0",
"ts-node": "^10.9.1"
},
"peerDependencies": {
"webpack": "^4 || ^5"
},
"bugs": {
"url": "https://github.com/signalfx/splunk-otel-js-browser/issues"
},
Expand Down
37 changes: 33 additions & 4 deletions packages/build-plugins/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,37 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

export class OllyWebWebpackPlugin {
public apply(): void {
console.log('apply OllyWebWebpackPlugin');
}
import { createUnplugin, UnpluginFactory } from 'unplugin';

import { BannerPlugin, WebpackPluginInstance } from 'webpack';
import { computeSourceMapId, getCodeSnippet } from './utils';

export interface OllyWebPluginOptions {
// define your plugin options here
}

const unpluginFactory: UnpluginFactory<OllyWebPluginOptions | undefined> = () => ({
name: 'OllyWebPlugin',
webpack(compiler) {
compiler.hooks.thisCompilation.tap('OllyWebPlugin', () => {
const bannerPlugin = new BannerPlugin({
banner: ({ chunk }) => {
if (!chunk.hash) {
return '';
}
const sourceMapId = computeSourceMapId(chunk.hash);
return getCodeSnippet(sourceMapId);
},
entryOnly: false,
footer: true,
include: /\.(js|mjs)$/,
raw: true,
});
bannerPlugin.apply(compiler);
});
}
});

const unplugin = createUnplugin(unpluginFactory);

export const ollyWebWebpackPlugin: (options: OllyWebPluginOptions) => WebpackPluginInstance = unplugin.webpack;
45 changes: 45 additions & 0 deletions packages/build-plugins/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright 2024 Splunk Inc.

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

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

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


import { createHash } from 'crypto';

/**
* Returns a standardized GUID value to use for a sourceMapId.
*
* @param content the source map file contents, or an already-computed hash of the source map (or its source files)
*/
export function computeSourceMapId(content: string): string {
const sha256 = createHash('sha256')
.update(content, 'utf-8')
.digest('hex');
const guid = [
sha256.slice(0, 8),
sha256.slice(8, 12),
sha256.slice(12, 16),
sha256.slice(16, 20),
sha256.slice(20, 32),
].join('-');
return guid;
}

// eslint-disable-next-line quotes
const SNIPPET_TEMPLATE = `;if (typeof window === 'object') { window.sourceMapIds = window.sourceMapIds || {}; let s = ''; try { throw new Error(); } catch (e) { s = (e.stack.match(/https?:\\/\\/[^\\s]+?(?::\\d+)?(?=:[\\d]+:[\\d]+)/) || [])[0]; } if (s) {window.sourceMapIds[s] = '__SOURCE_MAP_ID_PLACEHOLDER__';}};\n`;

export function getCodeSnippet(sourceMapId: string): string {
return SNIPPET_TEMPLATE.replace('__SOURCE_MAP_ID_PLACEHOLDER__', sourceMapId);
}

48 changes: 48 additions & 0 deletions packages/build-plugins/test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
Copyright 2024 Splunk Inc.

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

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

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

import { expect } from 'chai';
import { computeSourceMapId, getCodeSnippet } from '../src/utils';

describe('getCodeSnippet', function () {
it('inserts the source map id into the snippet', function () {
const code = getCodeSnippet('testid123');
expect(code).contains('window.sourceMapIds[s] = \'testid123\'');
});

it('does not throw error in a node environment', function () {
const code = getCodeSnippet('testid123');
// eslint-disable-next-line no-eval
eval(code);
});

it('does not throw error when appended to code that does not end with semicolon or new line', function () {
const code = 'let x = 5' + getCodeSnippet('testid123');
// eslint-disable-next-line no-eval
eval(code);
});

});

describe('computeSourceMapId', function () {
it('returns a consistent id in GUID format', function () {
const id = computeSourceMapId('console.log("Hello world")');

expect(id).eq('d77ec5d8-4fb5-fbc8-1897-54b54e939bcd');
expect(id).eq(computeSourceMapId('console.log("Hello world")'));
expect(id).not.eq(computeSourceMapId('console.log("a different snippet gets a different id");'));
});
});
3 changes: 2 additions & 1 deletion packages/build-plugins/tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"noEmitOnError": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"target": "ES2017",
"types": [
"node"
Expand All @@ -19,4 +20,4 @@
"exclude": [
"node_modules"
]
}
}
Loading