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

chore(atomic): update getAssetPath #4946

Merged
merged 18 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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: 2 additions & 0 deletions packages/atomic/jest/setup.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
module.exports = async () => {
// Mocking the ShadowRoot class to avoid errors in tests
globalThis.ShadowRoot = class ShadowRoot {};
// TODO: get rid of the mock once no longer running stencil tests
jest.mock('../src/utils/resource-url');
};
51 changes: 51 additions & 0 deletions packages/atomic/scripts/asset-path-transformer.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
isPropertyAccessExpression,
isIdentifier,
isMetaProperty,
visitEachChild,
visitNode,
SyntaxKind,
} from 'typescript';

/**
* Transforms occurrences of `import.meta.env.RESOURCE_URL` in the source file
* to `import.meta.url`.
*/
function resourceUrlTransformer(context) {
const {factory} = context;
return (sourceFile) => {
function visitor(node) {
// Check for import.meta.env.RESOURCE_URL
if (
isPropertyAccessExpression(node) &&
isIdentifier(node.name) &&
node.name.text === 'RESOURCE_URL'
) {
const envNode = node.expression;
if (
isPropertyAccessExpression(envNode) &&
isIdentifier(envNode.name) &&
envNode.name.text === 'env'
) {
const metaNode = envNode.expression;
if (
isMetaProperty(metaNode) &&
metaNode.keywordToken === SyntaxKind.ImportKeyword
) {
return factory.createPropertyAccessExpression(
factory.createMetaProperty(
SyntaxKind.ImportKeyword,
factory.createIdentifier('meta')
),
'url'
);
}
}
}
return visitEachChild(node, visitor, context);
}
return visitNode(sourceFile, visitor);
};
}

export default resourceUrlTransformer;
9 changes: 8 additions & 1 deletion packages/atomic/scripts/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
createProgram,
flattenDiagnosticMessageText,
} from 'typescript';
import resourceUrlTransformer from './asset-path-transformer.mjs';
import pathTransformer from './path-transform.mjs';
import svgTransformer from './svg-transform.mjs';

Expand All @@ -18,6 +19,12 @@ if (configArg === undefined) {
throw new Error('Missing --config=[PATH] argument');
}
const tsConfigPath = configArg.split('=')[1];
const isCDN = process.env.DEPLOYMENT_ENVIRONMENT === 'CDN';
const transformers = [
svgTransformer,
pathTransformer,
...(isCDN ? [resourceUrlTransformer] : []),
];

function loadTsConfig(configPath) {
const configFile = readConfigFile(configPath, sys.readFile);
Expand All @@ -39,7 +46,7 @@ function emit(program) {
const writeFile = undefined;
const emitOnlyDtsFiles = false;
const customTransformers = {
before: [svgTransformer, pathTransformer],
before: transformers,
};

return program.emit(
Expand Down
5 changes: 5 additions & 0 deletions packages/atomic/src/types/node.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
interface ImportMeta {
env: {
RESOURCE_URL?: string;
};
}
1 change: 1 addition & 0 deletions packages/atomic/src/utils/__mocks__/resource-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const getResourceUrl = () => undefined;
5 changes: 5 additions & 0 deletions packages/atomic/src/utils/resource-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// TODO: get rid of the mock once no longer running stencil tests

// import.meta is an ESM only feature and cannot be used in CJS.
// To avoid errors such as "SyntaxError: Cannot use 'import.meta' outside a module error" when running stencil tests, we need to mock this function in the tests.
export const getResourceUrl = () => import.meta.env?.RESOURCE_URL;
15 changes: 14 additions & 1 deletion packages/atomic/src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {getAssetPath} from '@stencil/core';
import {NODE_TYPES} from '@stencil/core/mock-doc';
import DOMPurify from 'dompurify';
import {getResourceUrl} from './resource-url';

/**
* Returns a function that can be executed only once
Expand Down Expand Up @@ -84,6 +84,19 @@ export function containsVisualElement(node: Node) {
return false;
}

export function getAssetPath(path: string): string {
const resourceUrl = getResourceUrl();
const baseUrl =
resourceUrl !== undefined
? new URL('./', resourceUrl).href
: new URL('./', window.document.baseURI).href;
const assetUrl = new URL(path, baseUrl);

return assetUrl.origin !== window.location.origin
? assetUrl.href
: assetUrl.pathname;
}

export function parseAssetURL(url: string, assetPath = './assets') {
const [, protocol, remainder] =
url.match(/^([a-z]+):\/\/(.*?)(\.svg)?$/) || [];
Expand Down
9 changes: 9 additions & 0 deletions packages/atomic/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import path from 'node:path';
import {defineConfig} from 'vitest/config';

const port = 63315;
const resourceUrl = `http://localhost:${port}/`;

export default defineConfig({
define: {
'import.meta.env.RESOURCE_URL': `"${resourceUrl}"`,
},
server: {
port: port,
},
resolve: {
alias: {
'@': path.resolve(import.meta.dirname, './'),
Expand Down
Loading