@iwsdk/cli 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -148,6 +148,131 @@ var mcpSurfaceMarkers = {
148
148
  * This source code is licensed under the MIT license found in the
149
149
  * LICENSE file in the root directory of this source tree.
150
150
  */
151
+ const DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS = 30_000;
152
+ const UI_RENDER_PREVIEW_TIMEOUT_MS = 60_000;
153
+ function getDefaultRuntimeCommandTimeoutMs(method) {
154
+ return method === 'ui_render_preview'
155
+ ? UI_RENDER_PREVIEW_TIMEOUT_MS
156
+ : DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS;
157
+ }
158
+ function describeValue(value) {
159
+ if (value === null) {
160
+ return 'null';
161
+ }
162
+ if (Array.isArray(value)) {
163
+ return 'array';
164
+ }
165
+ return typeof value;
166
+ }
167
+ function assertSchemaValue(value, schema, path) {
168
+ if (schema.oneOf?.length) {
169
+ const matches = schema.oneOf.filter((candidate) => {
170
+ try {
171
+ assertSchemaValue(value, candidate, path);
172
+ return true;
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ });
178
+ if (matches.length !== 1) {
179
+ throw new Error(`${path} must match exactly one supported shape`);
180
+ }
181
+ }
182
+ if (schema.anyOf?.length) {
183
+ const matches = schema.anyOf.some((candidate) => {
184
+ try {
185
+ assertSchemaValue(value, candidate, path);
186
+ return true;
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ });
192
+ if (!matches) {
193
+ throw new Error(`${path} must match a supported shape`);
194
+ }
195
+ }
196
+ if (schema.not) {
197
+ let matchesDisallowedSchema = true;
198
+ try {
199
+ assertSchemaValue(value, schema.not, path);
200
+ }
201
+ catch {
202
+ matchesDisallowedSchema = false;
203
+ }
204
+ if (matchesDisallowedSchema) {
205
+ throw new Error(`${path} uses a disallowed value`);
206
+ }
207
+ }
208
+ const typeMatches = schema.type == null ||
209
+ (schema.type === 'null' && value === null) ||
210
+ (schema.type === 'array' && Array.isArray(value)) ||
211
+ (schema.type === 'object' && isRecord$6(value)) ||
212
+ (schema.type === 'integer' && Number.isInteger(value)) ||
213
+ (schema.type === 'number' &&
214
+ typeof value === 'number' &&
215
+ Number.isFinite(value)) ||
216
+ (schema.type === 'string' && typeof value === 'string') ||
217
+ (schema.type === 'boolean' && typeof value === 'boolean');
218
+ if (!typeMatches) {
219
+ throw new Error(`${path} must be ${schema.type}; received ${describeValue(value)}`);
220
+ }
221
+ if (schema.enum && !schema.enum.includes(value)) {
222
+ throw new Error(`${path} must be one of: ${schema.enum.join(', ')}`);
223
+ }
224
+ if (typeof value === 'number') {
225
+ if (schema.minimum != null && value < schema.minimum) {
226
+ throw new Error(`${path} must be at least ${schema.minimum}`);
227
+ }
228
+ if (schema.exclusiveMinimum != null && value <= schema.exclusiveMinimum) {
229
+ throw new Error(`${path} must be greater than ${schema.exclusiveMinimum}`);
230
+ }
231
+ if (schema.maximum != null && value > schema.maximum) {
232
+ throw new Error(`${path} must be at most ${schema.maximum}`);
233
+ }
234
+ }
235
+ if (typeof value === 'string' &&
236
+ schema.pattern &&
237
+ !new RegExp(schema.pattern).test(value)) {
238
+ throw new Error(`${path} must match ${schema.pattern}`);
239
+ }
240
+ if (Array.isArray(value)) {
241
+ if (schema.minItems != null && value.length < schema.minItems) {
242
+ throw new Error(`${path} requires at least ${schema.minItems} items`);
243
+ }
244
+ if (schema.maxItems != null && value.length > schema.maxItems) {
245
+ throw new Error(`${path} allows at most ${schema.maxItems} items`);
246
+ }
247
+ if (schema.items) {
248
+ value.forEach((entry, index) => assertSchemaValue(entry, schema.items, `${path}[${index}]`));
249
+ }
250
+ }
251
+ if (isRecord$6(value)) {
252
+ const properties = schema.properties;
253
+ for (const required of schema.required ?? []) {
254
+ if (!Object.prototype.hasOwnProperty.call(value, required)) {
255
+ throw new Error(`${path}.${required} is required`);
256
+ }
257
+ }
258
+ for (const [name, entry] of Object.entries(value)) {
259
+ const propertySchema = properties?.[name];
260
+ if (propertySchema) {
261
+ assertSchemaValue(entry, propertySchema, `${path}.${name}`);
262
+ }
263
+ else if (!properties || schema.additionalProperties === true) {
264
+ continue;
265
+ }
266
+ else if (typeof schema.additionalProperties === 'object') {
267
+ assertSchemaValue(entry, schema.additionalProperties, `${path}.${name}`);
268
+ }
269
+ else {
270
+ const allowed = Object.keys(properties);
271
+ throw new Error(`${path} has unknown parameter "${name}"${allowed.length ? `; allowed: ${allowed.join(', ')}` : ''}`);
272
+ }
273
+ }
274
+ }
275
+ }
151
276
  const IWSDK_RUNTIME_LOGS_DIR = '.iwsdk/runtime/logs';
152
277
  const IWSDK_RUNTIME_SESSION_PATH = '.iwsdk/runtime/session.json';
153
278
  const IWSDK_RUNTIME_LAUNCH_PATH = '.iwsdk/runtime/launch.json';
@@ -2619,6 +2744,7 @@ function resolveRuntimeOperationRequest(operation, params) {
2619
2744
  Object.keys(paramsRecord).some((key) => key !== 'expectedTab')) {
2620
2745
  throw new Error('browser_screenshot does not accept parameters; it always captures the application runtime');
2621
2746
  }
2747
+ assertSchemaValue(params, operation.inputSchema, operation.mcpName);
2622
2748
  const commandParams = paramsRecord == null
2623
2749
  ? params
2624
2750
  : Object.fromEntries(Object.entries(paramsRecord).filter(([key]) => key !== 'expectedTab'));
@@ -8449,7 +8575,7 @@ async function confirmOpenedSceneReady(options, response, deadline, previousScen
8449
8575
  : 'browser_not_ready',
8450
8576
  });
8451
8577
  }
8452
- async function sendRuntimeCommand({ port, method, params, target, timeoutMs = 30000, runtimeSession, }) {
8578
+ async function sendRuntimeCommand({ port, method, params, target, timeoutMs = getDefaultRuntimeCommandTimeoutMs(method), runtimeSession, }) {
8453
8579
  if (runtimeSession?.browser?.status === 'not_launched') {
8454
8580
  throw new RuntimeCommandExecutionError(runtimeSession.browser.lastError?.message ??
8455
8581
  'No managed browser was launched. Run "iwsdk dev restart --open" to enable browser, scene, and runtime tools.', {
@@ -26273,13 +26399,78 @@ async function handleReferenceWarmup(options, context) {
26273
26399
  * This source code is licensed under the MIT license found in the
26274
26400
  * LICENSE file in the root directory of this source tree.
26275
26401
  */
26276
- const DEFAULT_TIMEOUT_MS = 30000;
26402
+ const COMMON_RUNTIME_OPTIONS = new Set([
26403
+ 'help',
26404
+ 'inputJson',
26405
+ 'raw',
26406
+ 'timeout',
26407
+ 'workspace',
26408
+ ]);
26409
+ const DIRECT_OPTION_ALIASES = {
26410
+ browser_get_console_logs: {
26411
+ count: { parameter: 'count', type: 'number' },
26412
+ level: { parameter: 'level', type: 'levels' },
26413
+ pattern: { parameter: 'pattern', type: 'string' },
26414
+ since: { parameter: 'since', type: 'number' },
26415
+ },
26416
+ ecs_step: {
26417
+ count: { parameter: 'count', type: 'number' },
26418
+ frames: { parameter: 'count', type: 'number' },
26419
+ delta: { parameter: 'delta', type: 'number' },
26420
+ },
26421
+ };
26422
+ function parseDirectValue(value, option, type) {
26423
+ if (typeof value !== 'string') {
26424
+ throw new Error(`--${option} requires a value`);
26425
+ }
26426
+ if (type === 'number') {
26427
+ const parsed = Number(value);
26428
+ if (!Number.isFinite(parsed)) {
26429
+ throw new Error(`--${option} must be a number`);
26430
+ }
26431
+ return parsed;
26432
+ }
26433
+ if (type === 'levels') {
26434
+ const levels = value.split(',').map((entry) => entry.trim());
26435
+ return levels.length === 1 ? levels[0] : levels;
26436
+ }
26437
+ return value;
26438
+ }
26439
+ function resolveRuntimeParams(operationName, options) {
26440
+ const aliases = DIRECT_OPTION_ALIASES[operationName] ?? {};
26441
+ const allowed = new Set([...COMMON_RUNTIME_OPTIONS, ...Object.keys(aliases)]);
26442
+ if (operationName === 'browser_screenshot' ||
26443
+ operationName === 'scene_screenshot' ||
26444
+ operationName === 'scene_render_file' ||
26445
+ operationName === 'ui_render_preview') {
26446
+ allowed.add('outputFile');
26447
+ }
26448
+ const unknown = Object.keys(options).filter((name) => !allowed.has(name));
26449
+ if (unknown.length > 0) {
26450
+ const flag = unknown[0].replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
26451
+ throw new Error(`Unknown option --${flag}. Runtime parameters must be passed through --input-json; run this command with --help for its schema.`);
26452
+ }
26453
+ const directEntries = Object.entries(aliases).filter(([name]) => options[name] !== undefined);
26454
+ if (typeof options.inputJson === 'string' && directEntries.length > 0) {
26455
+ throw new Error(`Do not combine --input-json with direct parameter aliases: ${directEntries.map(([name]) => `--${name}`).join(', ')}`);
26456
+ }
26457
+ if (typeof options.inputJson === 'string') {
26458
+ return safeJsonParse(options.inputJson, '--input-json');
26459
+ }
26460
+ return Object.fromEntries(directEntries.map(([name, alias]) => [
26461
+ alias.parameter,
26462
+ parseDirectValue(options[name], name, alias.type),
26463
+ ]));
26464
+ }
26277
26465
  function isRecord(value) {
26278
26466
  return typeof value === 'object' && value !== null && !Array.isArray(value);
26279
26467
  }
26280
26468
  function isScreenshotResult(value) {
26281
26469
  return isRecord(value) && typeof value.imageData === 'string';
26282
26470
  }
26471
+ function isBrowserRelaunchedResult(value) {
26472
+ return isRecord(value) && value.status === 'browser_relaunched';
26473
+ }
26283
26474
  function withBrowserStatus(result, session) {
26284
26475
  const browser = session.browser ?? null;
26285
26476
  const browserConnected = Boolean(session.browser?.connected);
@@ -26303,6 +26494,7 @@ async function saveScreenshot(result, requestedPath) {
26303
26494
  const outputPath = typeof requestedPath === 'string'
26304
26495
  ? requestedPath
26305
26496
  : path.join(os.tmpdir(), `iwsdk-screenshot-${Date.now()}.png`);
26497
+ await mkdir(path.dirname(outputPath), { recursive: true });
26306
26498
  await writeFile(outputPath, Buffer.from(result.imageData, 'base64'));
26307
26499
  return outputPath;
26308
26500
  }
@@ -26314,6 +26506,8 @@ async function handleRuntimeOperation(domain, action, options, io) {
26314
26506
  const available = RUNTIME_OPERATIONS.filter((entry) => entry.domain === domain).map((entry) => entry.action);
26315
26507
  throw new Error(`Unknown ${domain} command "${action}". Available: ${available.join(', ')}`);
26316
26508
  }
26509
+ const parsedParams = resolveRuntimeParams(operation.mcpName, options);
26510
+ const command = resolveRuntimeOperationRequest(operation, parsedParams);
26317
26511
  const workspaceRoot = await resolveWorkspaceRoot({
26318
26512
  cwd: io.cwd,
26319
26513
  workspace: typeof options.workspace === 'string' ? options.workspace : undefined,
@@ -26323,18 +26517,29 @@ async function handleRuntimeOperation(domain, action, options, io) {
26323
26517
  if (!session) {
26324
26518
  throw new Error(formatMissingRuntimeMessage(workspaceRoot));
26325
26519
  }
26326
- const parsedParams = typeof options.inputJson === 'string'
26327
- ? safeJsonParse(options.inputJson, '--input-json')
26328
- : {};
26329
- const command = resolveRuntimeOperationRequest(operation, parsedParams);
26330
- const rawResult = await sendRuntimeCommand({
26520
+ const sendOptions = {
26331
26521
  port: session.port,
26332
26522
  method: operation.wsMethod,
26333
26523
  params: command.params,
26334
26524
  target: command.target,
26335
- timeoutMs: parseIntegerOption(options.timeout, '--timeout', DEFAULT_TIMEOUT_MS),
26525
+ timeoutMs: parseIntegerOption(options.timeout, '--timeout', getDefaultRuntimeCommandTimeoutMs(operation.wsMethod)),
26336
26526
  runtimeSession: session,
26337
- });
26527
+ };
26528
+ let rawResult;
26529
+ try {
26530
+ rawResult = await sendRuntimeCommand(sendOptions);
26531
+ if (operation.mcpName === 'browser_screenshot' &&
26532
+ isBrowserRelaunchedResult(rawResult.result ?? rawResult)) {
26533
+ rawResult = await sendRuntimeCommand(sendOptions);
26534
+ }
26535
+ }
26536
+ catch (error) {
26537
+ if (operation.mcpName === 'xr_accept_session' &&
26538
+ error instanceof RuntimeCommandExecutionError) {
26539
+ error.message = `${error.message} Configure world.xr.offer as "once" or "always" before running iwsdk xr enter.`;
26540
+ }
26541
+ throw error;
26542
+ }
26338
26543
  const result = operation.mcpName === 'xr_get_session_status'
26339
26544
  ? withBrowserStatus(rawResult.result ?? rawResult, session)
26340
26545
  : (rawResult.result ?? rawResult);
@@ -26415,6 +26620,33 @@ function formatSchemaPropertyLines(propertyPath, schema, required, indent = 2) {
26415
26620
  }
26416
26621
  return lines;
26417
26622
  }
26623
+ function schemaExample(schema) {
26624
+ if (schema.enum?.length) {
26625
+ return schema.enum[0];
26626
+ }
26627
+ if (schema.oneOf?.length) {
26628
+ return schemaExample(schema.oneOf[0]);
26629
+ }
26630
+ if (schema.type === 'array') {
26631
+ return [schemaExample(schema.items ?? { type: 'string' })];
26632
+ }
26633
+ if (schema.type === 'object' || schema.properties) {
26634
+ return Object.fromEntries((schema.required ?? []).map((name) => [
26635
+ name,
26636
+ schemaExample(schema.properties?.[name] ?? { type: 'string' }),
26637
+ ]));
26638
+ }
26639
+ if (schema.type === 'number' || schema.type === 'integer') {
26640
+ return schema.minimum ?? 1;
26641
+ }
26642
+ if (schema.type === 'boolean') {
26643
+ return true;
26644
+ }
26645
+ if (schema.type === 'null') {
26646
+ return null;
26647
+ }
26648
+ return '<string>';
26649
+ }
26418
26650
  function buildRuntimeCommandHelp(domain, action) {
26419
26651
  const operation = getRuntimeOperationByCliPath(domain, action);
26420
26652
  if (!operation) {
@@ -26444,10 +26676,16 @@ function buildRuntimeCommandHelp(domain, action) {
26444
26676
  lines.push(...formatSchemaPropertyLines(name, schema, required.has(name)));
26445
26677
  }
26446
26678
  }
26447
- lines.push('', 'Options:', ' --input-json <json>', ' --timeout <ms>', ' --raw');
26679
+ lines.push('', 'Example:', ` iwsdk ${domain} ${action} --input-json '${JSON.stringify(schemaExample(operation.inputSchema))}'`, '', 'Options:', ' --input-json <json>', ' --timeout <ms>', ' --raw');
26448
26680
  if (writesScreenshot) {
26449
26681
  lines.push(' --output-file <path> Write the PNG to this path and return screenshotPath; takes precedence over --raw');
26450
26682
  }
26683
+ if (operation.mcpName === 'ecs_step') {
26684
+ lines.push(' --frames <count> Alias for input count', ' --count <count> Alias for input count', ' --delta <seconds> Alias for input delta');
26685
+ }
26686
+ if (operation.mcpName === 'browser_get_console_logs') {
26687
+ lines.push(' --level <levels> Comma-separated log-level alias', ' --count <count> Maximum log-count alias', ' --pattern <regex> Message-pattern alias', ' --since <timestamp> Timestamp alias');
26688
+ }
26451
26689
  return lines;
26452
26690
  }
26453
26691
  function buildRuntimeDomainHelp(domain) {
@@ -26611,11 +26849,11 @@ async function runCli(argv, io = {}) {
26611
26849
  stdout.write(`${buildReferenceCommandHelp(subcommand).join('\n')}\n`);
26612
26850
  return 0;
26613
26851
  }
26614
- if ((command === 'xr' ||
26852
+ if (command === 'xr' ||
26615
26853
  command === 'browser' ||
26616
26854
  command === 'scene' ||
26617
26855
  command === 'ui' ||
26618
- command === 'ecs')) {
26856
+ command === 'ecs') {
26619
26857
  stdout.write(`${(subcommand
26620
26858
  ? buildRuntimeCommandHelp(command, subcommand)
26621
26859
  : buildRuntimeDomainHelp(command)).join('\n')}\n`);
@@ -26699,6 +26937,9 @@ async function runCli(argv, io = {}) {
26699
26937
  case 'scene':
26700
26938
  case 'ui':
26701
26939
  case 'ecs':
26940
+ if (!subcommand) {
26941
+ throw new Error(buildRuntimeDomainHelp(command).join('\n'));
26942
+ }
26702
26943
  result = await handleRuntimeOperation(command, subcommand, parsed.options, context);
26703
26944
  break;
26704
26945
  default: