Skip to content
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: 2 additions & 0 deletions config/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ module.exports = {
appContentScriptJs: resolveModule(resolveApp, 'src/contentScript/index'),
appOptionsJs: resolveModule(resolveApp, 'src/options/index'),
appDevToolsJs: resolveModule(resolveApp, 'src/devtools/index'),
// Keep CRA's service worker path key defined so downstream fs.existsSync checks always receive a valid path.
swSrc: resolveModule(resolveApp, 'src/service-worker'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
Expand Down
31,786 changes: 7,733 additions & 24,053 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "graph-x-ray",
"version": "1.0.5",
"version": "1.0.6",
"private": true,
"dependencies": {
"@babel/core": "7.12.3",
"@babel/core": "^7.29.0",
"@fluentui/font-icons-mdl2": "^8.5.62",
"@fluentui/react": "^8.67.2",
"@fluentui/react-icons-mdl2-branded": "^1.2.8",
Expand Down Expand Up @@ -56,7 +56,7 @@
"react": "^17.0.2",
"react-app-polyfill": "^2.0.0",
"react-csv": "^2.0.3",
"react-dev-utils": "^11.0.1",
"react-dev-utils": "^11.0.4",
"react-dom": "^17.0.2",
"react-markdown": "^8.0.3",
"react-scroll-to-bottom": "^4.2.0",
Expand Down
2 changes: 1 addition & 1 deletion public/manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"manifest_version": 3,
"version": "1.0.5",
"version": "1.0.6",
"short_name": "Graph X-Ray",
"name": "Graph X-Ray",
"description": "Graph X-Ray converts your Microsoft admin portal clicks into ready-to-use code in PowerShell, C#, Python, and more.",
Expand Down
3 changes: 2 additions & 1 deletion scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ const bfj = require('bfj');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
// Use local helper to avoid deprecated fs.F_OK usage in older react-dev-utils.
const checkRequiredFiles = require('./utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
Expand Down
3 changes: 2 additions & 1 deletion scripts/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
// Use local helper to avoid deprecated fs.F_OK usage in older react-dev-utils.
const checkRequiredFiles = require('./utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
Expand Down
26 changes: 26 additions & 0 deletions scripts/utils/checkRequiredFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

const fs = require('fs');
const path = require('path');
const chalk = require('react-dev-utils/chalk');

function checkRequiredFiles(files) {
let currentFilePath;
try {
files.forEach(filePath => {
currentFilePath = filePath;
// Use fs.constants.F_OK to avoid Node deprecation warnings for fs.F_OK.
fs.accessSync(filePath, fs.constants.F_OK);
});
return true;
} catch (err) {
const dirName = path.dirname(currentFilePath);
const fileName = path.basename(currentFilePath);
console.log(chalk.red('Could not find a required file.'));
console.log(chalk.red(' Name: ') + chalk.cyan(fileName));
console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName));
return false;
}
}

module.exports = checkRequiredFiles;
146 changes: 106 additions & 40 deletions src/common/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,63 +3,129 @@ import { parseGraphUrl, GRAPH_DOMAINS, isUltraXRayDomain } from "./domains.js";
const devxEndPoint =
"https://devxapi-func-prod-eastus.azurewebsites.net/api/graphexplorersnippets";

const getPowershellCmd = async function (snippetLanguage, method, url, body) {
function formatPowerShellValue(val, indent) {
if (val === null) return "$null";
if (typeof val === "boolean") return val ? "$true" : "$false";
if (typeof val === "number") return String(val);

if (Array.isArray(val)) {
if (val.length === 0) return "@()";
const items = val.map(
(v) => `${indent}\t${formatPowerShellValue(v, indent + "\t")}`
);
return `@(\n${items.join("\n")}\n${indent})`;
}

if (typeof val === "object") {
const entries = Object.entries(val).map(
([k, v]) => `${indent}\t"${k}" = ${formatPowerShellValue(v, indent + "\t")}`
);
Comment thread
jorgeasaurus marked this conversation as resolved.
Resolved
return `@{\n${entries.join("\n")}\n${indent}}`;
}

const escaped = String(val).replace(/[`$"]/g, "`$&");
return `"${escaped}"`;
}

function buildBodyBlock(body) {
const lines = [];
lines.push("$params = @{");

try {
const parsed = JSON.parse(body);
for (const [key, value] of Object.entries(parsed)) {
lines.push(`\t"${key}" = ${formatPowerShellValue(value, "\t")}`);
}
Comment thread
jorgeasaurus marked this conversation as resolved.
Resolved
} catch {
lines.push(`\t# Raw body`);
body.split('\n').forEach(line => lines.push(`\t# ${line}`));
}
Comment thread
jorgeasaurus marked this conversation as resolved.
Resolved

lines.push("}");
return lines;
}

function generateLocalPowerShellSnippet(method, url, body) {
const { host, path } = parseGraphUrl(url);
// Strip any leading slashes from path before joining to avoid double slashes (e.g. "https://host//v1.0/...")
const fullUrl = `https://${host}/${path.replace(/^\/+/, '')}`;
// Escape $ signs in the URL with a backtick so PowerShell does not treat them as variable expansions inside double-quoted strings
const escapedUrl = fullUrl.replace(/\$/g, '`$');
const hasBody = body && body.trim().length > 0;

const lines = [];

if (hasBody) {
lines.push(...buildBodyBlock(body));
lines.push("");
}

let cmd = `Invoke-MgGraphRequest -Method ${method.toUpperCase()} -Uri "${escapedUrl}"`;
if (hasBody) {
cmd += ` -Body ($params | ConvertTo-Json -Depth 10) -ContentType "application/json"`;
}
lines.push(cmd);

return lines.join("\n");
}

async function getSnippetFromDevX(snippetLanguage, method, url, body) {
console.log("Get code snippet from DevX:", url, method);

// Check if the URL is from an Ultra X-Ray domain - if so, don't call devx

if (isUltraXRayDomain(url)) {
console.log("Skipping DevX call for Ultra X-Ray domain:", url);
return null;
}

const bodyText = body ?? ""; //Cast undefined and null to string
// Use the extracted parseGraphUrl function

const bodyText = body ?? "";
const { path: parsedPath, host } = parseGraphUrl(url);
const path = encodeURI(parsedPath); //Replace the spaces in OData with + as expected by API
const path = encodeURI(parsedPath);
const payload = `${method} ${path} HTTP/1.1\r\nHost: ${host}\r\nContent-Type: application/json\r\n\r\n${bodyText}`;
console.log("Payload:", payload);

const snippetParam = "?lang=%snippetLanguage%".replace(
"%snippetLanguage%",
snippetLanguage
);
const openApiParam = "&generation=openapi";

let devxSnippetUri = devxEndPoint;
if (snippetLanguage === "c#") {
devxSnippetUri = devxEndPoint;
} else if (["javascript", "java", "objective-c"].includes(snippetLanguage)) {
devxSnippetUri = devxEndPoint + snippetParam;
} else if (["go", "powershell", "python"].includes(snippetLanguage)) {
devxSnippetUri = devxEndPoint + snippetParam + openApiParam;
}
const devxSnippetUri = buildDevxUri(snippetLanguage);

try {
const response = await fetch(devxSnippetUri, {
headers: {
"content-type": "application/http",
},
headers: { "content-type": "application/http" },
method: "POST",
body: payload,
});
console.log("DevX responded");

if (response.ok) {
const resp = response.text();
console.log("DevX-Reponse", resp);
return resp;
} else {
const errorText = await response.text();
const errorMsg = `DevXError: ${response.status} ${response.statusText} for ${method} ${url} - Response: ${errorText}`;
console.log(errorMsg);
return null;
return await response.text();
}

const errorText = await response.text();
console.log(`DevXError: ${response.status} ${response.statusText} for ${method} ${url} - Response: ${errorText}`);
} catch (error) {
const errorMsg = `DevXError: Network/Request error for ${method} ${url} - ${
error.message || error
}`;
console.log(errorMsg, error);
console.log(`DevXError: Network/Request error for ${method} ${url} - ${error.message || error}`, error);
}
};

// Fall back to local generation for PowerShell when DevX fails
if (snippetLanguage === "powershell") {
console.log("Falling back to local PowerShell snippet generation");
return generateLocalPowerShellSnippet(method, url, bodyText);
}

return null;
}

function buildDevxUri(snippetLanguage) {
if (snippetLanguage === "c#") {
return devxEndPoint;
}

const langParam = `?lang=${snippetLanguage}`;

if (["go", "powershell", "python"].includes(snippetLanguage)) {
return `${devxEndPoint}${langParam}&generation=openapi`;
}

return `${devxEndPoint}${langParam}`;
}

// Preserve the original function name used throughout the codebase
const getPowershellCmd = getSnippetFromDevX;

const getRequestBody = async function (request) {
let requestBody = "";
Expand Down Expand Up @@ -329,4 +395,4 @@ const getCodeView = async function (snippetLanguage, request, version, harEntry
console.log("CodeView", codeView);
return codeView;
};
export { getPowershellCmd, getRequestBody, getResponseContent, getCodeView, getBatchCodeSnippets };
export { getPowershellCmd, getRequestBody, getResponseContent, getCodeView, getBatchCodeSnippets, generateLocalPowerShellSnippet };
Loading
Loading