-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathvalidation-helpers.js
More file actions
226 lines (207 loc) · 6.82 KB
/
Copy pathvalidation-helpers.js
File metadata and controls
226 lines (207 loc) · 6.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env node
// Shared utilities for Power Pages validation hook scripts.
// Provides common boilerplate so each validator only contains its unique logic.
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Exit 0 = success (allow). Exit 2 = blocking error (stderr is fed back to Claude).
const approve = () => { process.exit(0); };
const block = (reason) => {
process.stderr.write(reason);
process.exit(2);
};
/**
* Wraps stdin JSON parsing and try/catch boilerplate.
* Calls `callback(cwd)` with the parsed working directory.
* Approves automatically if cwd is missing or on any uncaught error.
*/
function runValidation(callback) {
let inputData = '';
process.stdin.on('data', chunk => (inputData += chunk));
process.stdin.on('end', async () => {
try {
const input = JSON.parse(inputData);
const cwd = input.cwd;
if (!cwd) approve();
await callback(cwd);
} catch {
approve();
}
});
}
/**
* Searches for a file or directory in `dir` and one level of subdirectories.
* @param {string} dir - Starting directory
* @param {string} target - Relative path to look for (e.g. 'powerpages.config.json')
* @returns {string|null} Full path if found, null otherwise
*/
function findPath(dir, target) {
const direct = path.join(dir, target);
if (fs.existsSync(direct)) return direct;
try {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.git') {
const sub = path.join(dir, entry.name, target);
if (fs.existsSync(sub)) return sub;
}
}
} catch {}
return null;
}
/**
* Finds the project root directory (containing powerpages.config.json).
* @returns {string|null} Project root path, or null
*/
function findProjectRoot(dir) {
let current = path.resolve(dir);
while (true) {
const configPath = path.join(current, 'powerpages.config.json');
if (fs.existsSync(configPath)) {
return current;
}
const parent = path.dirname(current);
if (parent === current) {
break;
}
current = parent;
}
const fallbackConfigPath = findPath(dir, 'powerpages.config.json');
return fallbackConfigPath ? path.dirname(fallbackConfigPath) : null;
}
/**
* Finds a subdirectory inside .powerpages-site/.
* @param {string} dir - Starting directory
* @param {string} subdir - Subdirectory name (e.g. 'site-settings', 'web-roles')
* @returns {string|null} Full path to the subdirectory, or null
*/
function findPowerPagesSiteDir(dir, subdir) {
return findPath(dir, path.join('.powerpages-site', subdir));
}
/** UUID v4 validation regex */
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* Gets an Azure CLI access token for the given resource URL.
* The `--allow-no-subscriptions` flag is only valid on `az login` (other `az`
* subcommands reject it as an unrecognized argument), so it must not be passed
* here. Accounts without a subscription can still mint AAD-scoped tokens after
* signing in via `az login --allow-no-subscriptions`.
* @returns {string|null} Access token, or null if unavailable
*/
function getAuthToken(resourceUrl) {
try {
return execSync(
`az account get-access-token --resource "${resourceUrl}" --query accessToken -o tsv`,
{ encoding: 'utf8', timeout: 15000 }
).trim();
} catch {
return null;
}
}
/**
* Gets the environment URL from `pac env who`.
* @returns {string|null} Environment URL, or null
*/
function getEnvironmentUrl() {
try {
const output = execSync('pac env who', { encoding: 'utf8', timeout: 15000 });
const match = output.match(/Environment URL:\s*(https:\/\/[^\s]+)/i);
return match ? match[1].replace(/\/+$/, '') : null;
} catch {
return null;
}
}
/**
* Gets PAC CLI auth info (environment ID and cloud).
* @returns {{ environmentId: string, cloud: string }|null}
*/
function getPacAuthInfo() {
try {
const output = execSync('pac auth who', { encoding: 'utf8', timeout: 15000 });
const envMatch = output.match(/Environment ID:\s*([0-9a-fA-F-]+)/i);
const cloudMatch = output.match(/Cloud:\s*(\S+)/i);
if (!envMatch) return null;
return {
environmentId: envMatch[1],
cloud: cloudMatch ? cloudMatch[1] : 'Public',
};
} catch {
return null;
}
}
/**
* Makes an HTTP/HTTPS request using Node.js built-in modules (cross-platform, no PowerShell).
* Returns a Promise — callers must use `await`.
* @param {object} options
* @param {string} options.url - Full URL to request
* @param {string} [options.method='GET'] - HTTP method
* @param {object} [options.headers={}] - Request headers
* @param {string} [options.body=null] - Request body (string)
* @param {boolean} [options.includeHeaders=false] - Include response headers in result
* @param {number} [options.timeout=15000] - Timeout in ms
* @returns {Promise<{ statusCode: number, body: string, headers?: object } | { error: string }>}
*/
function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHeaders = false, timeout = 15000 }) {
return new Promise((resolve) => {
const https = require('https');
const http = require('http');
const u = new URL(url);
const mod = u.protocol === 'https:' ? https : http;
const req = mod.request(
{
method,
headers,
hostname: u.hostname,
port: u.port || undefined,
path: u.pathname + u.search,
timeout,
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
const result = { statusCode: res.statusCode, body: data };
if (includeHeaders) result.headers = res.headers;
resolve(result);
});
}
);
req.on('error', (e) => resolve({ error: e.message }));
req.on('timeout', () => {
req.destroy();
resolve({ error: 'Request timed out' });
});
if (body) req.write(body);
req.end();
});
}
/** Cloud → Power Platform API base URL mapping */
const CLOUD_TO_API = {
'Public': 'https://api.powerplatform.com',
'UsGov': 'https://api.gov.powerplatform.microsoft.us',
'UsGovHigh': 'https://api.high.powerplatform.microsoft.us',
'UsGovDod': 'https://api.appsplatform.us',
'China': 'https://api.powerplatform.partner.microsoftonline.cn',
};
/** Cloud → Power Pages site URL domain mapping */
const CLOUD_TO_SITE_DOMAIN = {
'Public': 'powerappsportals.com',
'UsGov': 'powerappsportals.us',
'UsGovHigh': 'high.powerappsportals.us',
'UsGovDod': 'appsplatform.us',
'China': 'powerappsportals.cn',
};
module.exports = {
approve,
block,
runValidation,
findPath,
findProjectRoot,
findPowerPagesSiteDir,
UUID_REGEX,
getAuthToken,
makeRequest,
getEnvironmentUrl,
getPacAuthInfo,
CLOUD_TO_API,
CLOUD_TO_SITE_DOMAIN,
};