@revoengine/cli 2.1.1 → 2.2.0

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +111 -12
  3. package/dist/src/application-access.d.ts +4 -0
  4. package/dist/src/application-access.js +18 -0
  5. package/dist/src/application-cors.d.ts +2 -0
  6. package/dist/src/application-cors.js +19 -0
  7. package/dist/src/argument-contract.js +24 -4
  8. package/dist/src/automation-contract.generated.d.ts +165 -6
  9. package/dist/src/automation-contract.generated.js +198 -6
  10. package/dist/src/cli.js +10 -2
  11. package/dist/src/client.d.ts +53 -1
  12. package/dist/src/client.js +84 -0
  13. package/dist/src/commands/applications.d.ts +2 -0
  14. package/dist/src/commands/applications.js +44 -0
  15. package/dist/src/commands/emulate.d.ts +1 -0
  16. package/dist/src/commands/emulate.js +79 -3
  17. package/dist/src/commands/index.d.ts +2 -0
  18. package/dist/src/commands/index.js +2 -0
  19. package/dist/src/commands/migrate.js +10 -2
  20. package/dist/src/commands/sites.d.ts +2 -0
  21. package/dist/src/commands/sites.js +156 -0
  22. package/dist/src/component-lock.d.ts +2 -1
  23. package/dist/src/component-lock.js +22 -1
  24. package/dist/src/endpoint-application.d.ts +25 -0
  25. package/dist/src/endpoint-application.js +75 -0
  26. package/dist/src/endpoint-emulator.d.ts +5 -0
  27. package/dist/src/endpoint-emulator.js +29 -0
  28. package/dist/src/endpoint-storage-transports.d.ts +2 -0
  29. package/dist/src/endpoint-storage-transports.js +8 -0
  30. package/dist/src/metadata-backfill.d.ts +1 -1
  31. package/dist/src/metadata-backfill.js +10 -1
  32. package/dist/src/migration.d.ts +6 -2
  33. package/dist/src/migration.js +104 -41
  34. package/dist/src/project.d.ts +8 -1
  35. package/dist/src/project.js +4 -0
  36. package/dist/src/request-contract.d.ts +5 -0
  37. package/dist/src/request-contract.js +12 -0
  38. package/dist/src/resource-inventory.d.ts +4 -2
  39. package/dist/src/resource-inventory.js +16 -1
  40. package/dist/src/resource-syncs/account-principal.d.ts +2 -0
  41. package/dist/src/resource-syncs/account-principal.js +3 -0
  42. package/dist/src/resource-syncs/application-principals.d.ts +60 -0
  43. package/dist/src/resource-syncs/application-principals.js +151 -0
  44. package/dist/src/resource-syncs/application-sync.d.ts +110 -0
  45. package/dist/src/resource-syncs/application-sync.js +328 -0
  46. package/dist/src/resource-syncs/endpoint-sync.d.ts +38 -0
  47. package/dist/src/resource-syncs/endpoint-sync.js +278 -14
  48. package/dist/src/resource-syncs/group-sync.d.ts +12 -0
  49. package/dist/src/resource-syncs/group-sync.js +60 -6
  50. package/dist/src/resource-syncs/runtime-definition-validation.js +26 -1
  51. package/dist/src/resource-syncs/service-account-sync.d.ts +10 -0
  52. package/dist/src/resource-syncs/service-account-sync.js +32 -4
  53. package/dist/src/reviewed-plan.js +2 -2
  54. package/dist/src/sync-omit-write-fence.js +4 -1
  55. package/dist/src/sync-omit.d.ts +1 -1
  56. package/dist/src/sync-omit.js +7 -2
  57. package/dist/src/tracked-resources.d.ts +1 -1
  58. package/dist/src/tracked-resources.js +3 -2
  59. package/dist/src/types.d.ts +30 -0
  60. package/dist/src/ui.js +2 -0
  61. package/dist/src/workspace-diff.js +1 -0
  62. package/dist/src/workspace-digests.js +2 -0
  63. package/dist/src/workspace-prune.js +67 -9
  64. package/package.json +2 -2
@@ -1,11 +1,15 @@
1
1
  import { once } from 'node:events';
2
2
  import { realpath } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
+ import { isIP } from 'node:net';
5
+ import { usesEndpointStorageTransport } from "../endpoint-storage-transports.js";
6
+ import { ApiError } from "../client.js";
4
7
  import { createEndpointEmulator, assertEmulatorWorkspace, DEFAULT_EMULATOR_HOST, isLoopbackEmulatorHost, normalizeEmulatorHost, } from "../endpoint-emulator.js";
5
8
  import { buildSandboxDebugUrl, extractSandboxEndpoint, extractServiceEndpoint, readProjectStableKeyName, REVO_PROJECT_DIR } from "../project.js";
6
9
  import { resolveAuthenticatedInstance } from "../resource-target.js";
7
10
  import { requireProjectLayout } from "../resource-syncs/util.js";
8
11
  import { writeJsonFile } from "../utils.js";
12
+ import { DEFAULT_ENDPOINT_APPLICATION_KEY, DEFAULT_ENDPOINT_APPLICATION_ID, isNamedApplicationKey, resolveEndpointApplication } from "../endpoint-application.js";
9
13
  function formatRequestEvent(event, json) {
10
14
  const time = new Date().toISOString();
11
15
  if (json) {
@@ -23,11 +27,36 @@ function formatRequestEvent(event, json) {
23
27
  : event.execution === 'sandbox' ? ' · Sandbox preview' : '';
24
28
  return `${request} → ${status} (${event.durationMs} ms)${execution}`;
25
29
  }
30
+ function publishedApplicationRouteMatches(pattern, pathname) {
31
+ const normalize = (value) => value.replace(/\/{2,}/g, '/').replace(/\/+$/, '') || '/';
32
+ const expected = normalize(pattern).split('/');
33
+ const actual = normalize(pathname).split('/');
34
+ return expected.length === actual.length && expected.every((part, index) => part === '@' || part.startsWith(':') || part === actual[index]);
35
+ }
36
+ export function applicationPublishedRunUrl(runBase, applicationKey, instanceId) {
37
+ const url = new URL(runBase);
38
+ const label = `${applicationKey}--${instanceId.toLowerCase()}`;
39
+ if (!isNamedApplicationKey(applicationKey) || instanceId !== instanceId.trim() || !/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(instanceId.toLowerCase())
40
+ || label.length > 63 || isIP(url.hostname) !== 0 || !/^https?:$/.test(url.protocol) || url.username || url.password || url.pathname !== '/'
41
+ || !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(url.hostname) || url.hostname.split('.').some(part => part.length > 63)) {
42
+ throw new Error('Named Application published forwarding requires a valid Run DNS base and an Application/verified instance hostname label of at most 63 characters. Use the real Run URL with a verified instance slug for longer keys.');
43
+ }
44
+ url.hostname = `${label}.${url.hostname}`;
45
+ if (url.hostname.length > 253)
46
+ throw new Error('Application Run hostname exceeds the DNS name limit.');
47
+ url.search = '';
48
+ url.hash = '';
49
+ return url;
50
+ }
26
51
  export async function handleEmulateCommand(context) {
27
52
  if (context.args._[1] !== 'endpoints' || context.args._.length !== 2) {
28
- throw new Error('Usage: revo emulate endpoints [--mode=local|published] [--read-only=true|false] [--project <name>] [--host <address>] [--port <port>] [--skip-validate] [--no-watch]');
53
+ throw new Error('Usage: revo emulate endpoints [--application <key|@default>] [--mode=local|published] [--read-only=true|false] [--project <name>] [--host <address>] [--port <port>] [--skip-validate] [--no-watch]');
29
54
  }
30
55
  const readOnly = context.args['read-only'] !== 'false';
56
+ const applicationKey = String(context.args.application ?? DEFAULT_ENDPOINT_APPLICATION_KEY);
57
+ if (applicationKey !== DEFAULT_ENDPOINT_APPLICATION_KEY && !isNamedApplicationKey(applicationKey)) {
58
+ throw new Error('--application must be an exact Application key or @default.');
59
+ }
31
60
  const mode = context.args.mode ?? 'local';
32
61
  if (mode !== 'local' && mode !== 'published')
33
62
  throw new Error('--mode must be local or published.');
@@ -67,11 +96,54 @@ export async function handleEmulateCommand(context) {
67
96
  const run = extractServiceEndpoint(profile, 'run');
68
97
  if (!run)
69
98
  throw new Error('The authenticated project did not advertise a Run endpoint.');
99
+ if (applicationKey !== DEFAULT_ENDPOINT_APPLICATION_KEY)
100
+ await resolveEndpointApplication(context.client, { key: applicationKey });
101
+ const publishedBase = applicationKey === DEFAULT_ENDPOINT_APPLICATION_KEY ? new URL(run)
102
+ : applicationPublishedRunUrl(run, applicationKey, context.client.instance);
103
+ let unknownFormatWarning = false;
70
104
  server = createEndpointEmulator({
71
105
  ...listenerOptions,
106
+ preflightPublishedEndpoint: async ({ method, url }) => {
107
+ let endpoints;
108
+ if (applicationKey !== DEFAULT_ENDPOINT_APPLICATION_KEY) {
109
+ const application = await resolveEndpointApplication(context.client, { key: applicationKey });
110
+ endpoints = await context.client.listApplicationEndpoints(application.serviceId);
111
+ if (endpoints.some(endpoint => endpoint.serviceId !== application.serviceId)) {
112
+ throw new Error('Application endpoint catalog did not preserve the selected Application identity.');
113
+ }
114
+ }
115
+ else {
116
+ try {
117
+ endpoints = (await context.client.listAllEndpoints()).endpoints.filter(endpoint => !endpoint.serviceId || endpoint.serviceId === DEFAULT_ENDPOINT_APPLICATION_ID);
118
+ }
119
+ catch (error) {
120
+ if (!(error instanceof ApiError) || error.status !== 403)
121
+ throw error;
122
+ // Legacy RUN-only principals need no new management permission.
123
+ // Without metadata this remains ordinary bounded HTTP forwarding;
124
+ // it cannot establish native transport support or reject it early.
125
+ if (!unknownFormatWarning) {
126
+ unknownFormatWarning = true;
127
+ const message = 'Endpoint catalog access is denied. Default preview retains legacy HTTP forwarding with a 2 MiB request limit; native Storage formats are unknown and cannot be validated here. Use the real RUN endpoint for streaming.';
128
+ context.println(json ? JSON.stringify({ event: 'warning', code: 'ENDPOINT_FORMAT_UNKNOWN', message }) : message);
129
+ }
130
+ return undefined;
131
+ }
132
+ }
133
+ const matches = endpoints.filter(endpoint => endpoint.active === true && !endpoint.deletedAt && !endpoint.deletedBy && endpoint.method === method
134
+ && typeof endpoint.path === 'string' && publishedApplicationRouteMatches(endpoint.path, url.pathname));
135
+ if (applicationKey !== DEFAULT_ENDPOINT_APPLICATION_KEY && !matches.length)
136
+ return { status: 404, body: { code: 'ENDPOINT_NOT_FOUND', message: 'No active endpoint matches the selected Application.' } };
137
+ const exact = matches.filter(endpoint => typeof endpoint.path === 'string' && !endpoint.path.split('/').some(part => part === '@' || part.startsWith(':')));
138
+ if ((exact.length ? exact : matches).some(endpoint => usesEndpointStorageTransport(endpoint.options)))
139
+ return { status: 501,
140
+ body: { code: 'ENDPOINT_STORAGE_TRANSPORT_UNSUPPORTED', message: 'The CLI emulator buffers HTTP data and cannot validate native Storage upload or download. Call the real RUN endpoint directly.' } };
141
+ return undefined;
142
+ },
72
143
  runPublishedEndpoint: async ({ method, url, headers, body, signal }) => {
73
- const upstream = new URL(run);
74
- upstream.pathname = upstream.pathname.replace(/\/+$/, '') + url.pathname;
144
+ const upstream = new URL(publishedBase);
145
+ upstream.pathname = upstream.pathname.replace(/\/+$/, '')
146
+ + url.pathname;
75
147
  upstream.search = url.search;
76
148
  upstream.hash = '';
77
149
  const result = await context.client.request(method, upstream.toString(), {
@@ -100,6 +172,7 @@ export async function handleEmulateCommand(context) {
100
172
  server = createEndpointEmulator({
101
173
  ...listenerOptions,
102
174
  workspaceRoot,
175
+ applicationKey,
103
176
  stableKeyName: readProjectStableKeyName(projectRoot),
104
177
  readOnly,
105
178
  skipValidate,
@@ -138,6 +211,7 @@ export async function handleEmulateCommand(context) {
138
211
  }
139
212
  if (json) {
140
213
  context.println(JSON.stringify({ event: 'ready', port, localOnly, readOnly, mode,
214
+ ...(applicationKey === DEFAULT_ENDPOINT_APPLICATION_KEY ? {} : { application: applicationKey }),
141
215
  ...(skipValidate ? { skipValidate } : {}) }));
142
216
  }
143
217
  else {
@@ -151,6 +225,8 @@ export async function handleEmulateCommand(context) {
151
225
  }
152
226
  if (skipValidate)
153
227
  context.println('Sandbox preview skips low-code source analysis.');
228
+ if (applicationKey !== DEFAULT_ENDPOINT_APPLICATION_KEY)
229
+ context.println(`Application: ${applicationKey}`);
154
230
  if (watch)
155
231
  context.println('Watching HTTP requests.');
156
232
  if (mode === 'local')
@@ -3,6 +3,7 @@ export * from './component.ts';
3
3
  export * from './database-tables.ts';
4
4
  export * from './database-views.ts';
5
5
  export * from './endpoints.ts';
6
+ export * from './applications.ts';
6
7
  export * from './emulate.ts';
7
8
  export * from './env.ts';
8
9
  export * from './events.ts';
@@ -20,4 +21,5 @@ export * from './terminal.ts';
20
21
  export * from './schedules.ts';
21
22
  export * from './agents.ts';
22
23
  export * from './studio.ts';
24
+ export * from './sites.ts';
23
25
  export * from './tests.ts';
@@ -3,6 +3,7 @@ export * from "./component.js";
3
3
  export * from "./database-tables.js";
4
4
  export * from "./database-views.js";
5
5
  export * from "./endpoints.js";
6
+ export * from "./applications.js";
6
7
  export * from "./emulate.js";
7
8
  export * from "./env.js";
8
9
  export * from "./events.js";
@@ -20,4 +21,5 @@ export * from "./terminal.js";
20
21
  export * from "./schedules.js";
21
22
  export * from "./agents.js";
22
23
  export * from "./studio.js";
24
+ export * from "./sites.js";
23
25
  export * from "./tests.js";
@@ -31,6 +31,7 @@ const RESOURCE_ALIASES = {
31
31
  'job-templates': 'job-template',
32
32
  jobtemplate: 'job-template',
33
33
  jobtemplates: 'job-template',
34
+ application: 'application', applications: 'application', app: 'application', apps: 'application',
34
35
  endpoint: 'endpoint',
35
36
  endpoints: 'endpoint',
36
37
  schedule: 'schedule',
@@ -56,6 +57,7 @@ const MIGRATION_RESOURCE_ORDER = [
56
57
  'agent-plugin',
57
58
  'agent',
58
59
  'job-template',
60
+ 'application',
59
61
  'endpoint',
60
62
  'schedule',
61
63
  'event',
@@ -76,7 +78,7 @@ function readMigrationResources(context, commandLabel = 'Migration') {
76
78
  for (const value of values) {
77
79
  const resource = RESOURCE_ALIASES[value];
78
80
  if (!resource) {
79
- throw new Error(`${commandLabel} currently supports: database-table, database-view, component, job-template, endpoint, schedule, event, group, role-group, service-account, agent-plugin, agent, or all.`);
81
+ throw new Error(`${commandLabel} currently supports: database-table, database-view, component, application, job-template, endpoint, schedule, event, group, role-group, service-account, agent-plugin, agent, or all.`);
80
82
  }
81
83
  if (!resources.includes(resource)) {
82
84
  resources.push(resource);
@@ -251,6 +253,12 @@ function printMigrationPlan(context, plan) {
251
253
  blockers: phase.blockers,
252
254
  });
253
255
  }
256
+ if (phase.resource === 'application' && plan.applications) {
257
+ context.println('Applications');
258
+ for (const item of plan.applications.items)
259
+ context.println(` ${item.status} ${item.stableKey}`);
260
+ continue;
261
+ }
254
262
  if (phase.resource === 'endpoint' && plan.endpoints) {
255
263
  printSyncPlan(context.println, {
256
264
  title: `${phaseLabel} phase ${phase.order} / Endpoint`,
@@ -638,7 +646,7 @@ async function executeMigrateCommand(context) {
638
646
  const dryRun = readBoolFlag(context.args, ['dry-run']);
639
647
  const subcommand = dryRun ? 'plan' : requestedSubcommand;
640
648
  if (requestedSubcommand !== 'plan' && requestedSubcommand !== 'run' && requestedSubcommand !== 'verify') {
641
- throw new Error('Unknown migrate command. Usage: revo migrate <plan|run|verify> --from <env> --to <env> [--resources database-table,database-view,component,job-template,endpoint,schedule,event,group,role-group,service-account,agent-plugin,agent] [--skip-groups] [--dry-run]');
649
+ throw new Error('Unknown migrate command. Usage: revo migrate <plan|run|verify> --from <env> --to <env> [--resources database-table,database-view,component,application,job-template,endpoint,schedule,event,group,role-group,service-account,agent-plugin,agent] [--skip-groups] [--dry-run]');
642
650
  }
643
651
  const input = readMigrationInput(context);
644
652
  const json = readBoolFlag(context.args, ['json']);
@@ -0,0 +1,2 @@
1
+ import type { CommandContext } from '../types.ts';
2
+ export declare function handleSitesCommand(context: CommandContext): Promise<void>;
@@ -0,0 +1,156 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { validateCommandArguments } from "../argument-contract.js";
4
+ import { extractProfileInstanceId } from "../client.js";
5
+ import { extractServiceEndpoint, resolveProjectRoot } from "../project.js";
6
+ import { readFlag } from "../utils.js";
7
+ const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
8
+ const maxFileBytes = 2 * 1024 * 1024;
9
+ const maxHostingBytes = 16 * 1024;
10
+ function uuid(value, label) {
11
+ if (!value || !uuidPattern.test(value))
12
+ throw new Error(`${label} must be a UUID.`);
13
+ return value;
14
+ }
15
+ function observedRevision(value) {
16
+ const revision = value && /^(0|[1-9][0-9]*)$/.test(value) ? Number(value) : NaN;
17
+ if (!Number.isSafeInteger(revision))
18
+ throw new Error('Pass the observed nonnegative --revision.');
19
+ return revision;
20
+ }
21
+ function readBoundedFile(cwd, file, limit = maxFileBytes, flags = 0) {
22
+ if (!file)
23
+ throw new Error('Choose an input file.');
24
+ const fd = openSync(path.resolve(cwd, file), constants.O_RDONLY | constants.O_NONBLOCK | flags);
25
+ try {
26
+ const stat = fstatSync(fd);
27
+ if (!stat.isFile() || stat.size > limit)
28
+ throw new Error(`Site input must be a regular file up to ${limit} bytes.`);
29
+ const bytes = Buffer.alloc(stat.size + 1);
30
+ let length = 0;
31
+ while (length < bytes.length) {
32
+ const read = readSync(fd, bytes, length, bytes.length - length, null);
33
+ if (!read)
34
+ break;
35
+ length += read;
36
+ }
37
+ if (length !== stat.size)
38
+ throw new Error('Site input changed while reading. Retry with a complete file.');
39
+ return bytes.subarray(0, length);
40
+ }
41
+ finally {
42
+ closeSync(fd);
43
+ }
44
+ }
45
+ function readHostingConfig(cwd) {
46
+ const root = resolveProjectRoot(cwd) || cwd;
47
+ let content;
48
+ try {
49
+ if (lstatSync(path.join(root, 'revo.hosting.json')).isSymbolicLink()) {
50
+ throw new Error('A hosting config must be a regular file.');
51
+ }
52
+ content = readBoundedFile(root, 'revo.hosting.json', maxHostingBytes, constants.O_NOFOLLOW);
53
+ }
54
+ catch (error) {
55
+ if (error.code === 'ENOENT')
56
+ return undefined;
57
+ throw new Error('revo.hosting.json must be a readable regular file of at most 16 KiB.');
58
+ }
59
+ let value;
60
+ try {
61
+ value = JSON.parse(content.toString('utf8'));
62
+ }
63
+ catch {
64
+ throw new Error('revo.hosting.json must contain valid JSON.');
65
+ }
66
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
67
+ throw new Error('revo.hosting.json must contain a JSON object.');
68
+ }
69
+ return value;
70
+ }
71
+ function studioLink(origin, instanceId, siteId) {
72
+ if (!origin)
73
+ throw new Error('The target did not return a Studio origin. Pass --studio-origin.');
74
+ const url = new URL(origin);
75
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
76
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash
77
+ || (url.protocol !== 'https:' && !(loopback && url.protocol === 'http:'))) {
78
+ throw new Error('Studio origin must be HTTPS or HTTP on loopback, without a path or credentials.');
79
+ }
80
+ url.pathname = `/${instanceId}/studio/sites`;
81
+ url.searchParams.set('siteId', siteId);
82
+ return url.href;
83
+ }
84
+ export async function handleSitesCommand(context) {
85
+ validateCommandArguments(context.args);
86
+ const { args, client } = context;
87
+ const action = args._[1] || 'list';
88
+ const flag = (name) => readFlag(args, [name]);
89
+ if (action === 'list') {
90
+ context.print(await client.listStudioSites());
91
+ return;
92
+ }
93
+ if (action === 'create') {
94
+ const key = flag('key');
95
+ const name = flag('name')?.trim();
96
+ if (!key || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(key) || key.length > 40 || ['default', 'preview'].includes(key)) {
97
+ throw new Error('Pass a lowercase --key up to 40 characters, with digits and single hyphens.');
98
+ }
99
+ if (!name)
100
+ throw new Error('Pass --name for the Site.');
101
+ context.print(await client.createStudioSite({ key, name, description: flag('description') }));
102
+ return;
103
+ }
104
+ const siteId = uuid(args._[2], 'Site ID');
105
+ if (action === 'show') {
106
+ context.print(await client.getStudioSite(siteId));
107
+ return;
108
+ }
109
+ if (action === 'link') {
110
+ await client.getStudioSite(siteId);
111
+ const profile = await client.me();
112
+ const instanceId = uuid(client.instance || extractProfileInstanceId(profile), 'Instance ID');
113
+ context.print({ url: studioLink(flag('studio-origin') || extractServiceEndpoint(profile, 'app'), instanceId, siteId) });
114
+ return;
115
+ }
116
+ if (action === 'update-files') {
117
+ const expectedRevision = observedRevision(flag('revision'));
118
+ const files = JSON.parse(readBoundedFile(context.cwd, flag('files')).toString('utf8'));
119
+ if (!Array.isArray(files) || !files.length || files.some(file => !file || typeof file.path !== 'string' || typeof file.content !== 'string')) {
120
+ throw new Error('Pass a JSON array of Site files with path and content.');
121
+ }
122
+ context.print(await client.updateStudioSite(siteId, { expectedRevision, files: files.map(({ path, content }) => ({ path, content })) }));
123
+ return;
124
+ }
125
+ if (action === 'configure') {
126
+ const expectedRevision = observedRevision(flag('revision'));
127
+ const value = JSON.parse(readBoundedFile(context.cwd, flag('body-file')).toString('utf8'));
128
+ if (!value || typeof value !== 'object' || Array.isArray(value)
129
+ || !Object.keys(value).length || Object.keys(value).some(key => !['name', 'description', 'access', 'bindings', 'authConnectionId'].includes(key))) {
130
+ throw new Error('Configuration JSON must set name, description, access, bindings or authConnectionId.');
131
+ }
132
+ context.print(await client.updateStudioSite(siteId, { ...value, expectedRevision }));
133
+ return;
134
+ }
135
+ if (action === 'build') {
136
+ const expectedRevision = observedRevision(flag('revision'));
137
+ const file = flag('zip');
138
+ const archiveBase64 = file ? readBoundedFile(context.cwd, file).toString('base64') : undefined;
139
+ const hostingConfig = readHostingConfig(context.cwd);
140
+ context.print(await client.buildStudioSite(siteId, { expectedRevision, archiveBase64, ...(hostingConfig ? { hostingConfig } : {}) }));
141
+ return;
142
+ }
143
+ if (action === 'unpublish') {
144
+ const expectedActiveReleaseId = uuid(flag('expected-active'), 'Expected active release');
145
+ context.print(await client.unpublishStudioSite(siteId, { expectedActiveReleaseId }));
146
+ return;
147
+ }
148
+ const releaseId = uuid(flag('release'), 'Release ID');
149
+ if (action === 'preview') {
150
+ context.print(await client.previewStudioSite(siteId, { releaseId }));
151
+ return;
152
+ }
153
+ const active = flag('expected-active');
154
+ const expectedActiveReleaseId = active === 'none' ? null : uuid(active, 'Expected active release');
155
+ context.print(await client.publishStudioSite(siteId, { releaseId, expectedActiveReleaseId }));
156
+ }
@@ -144,6 +144,7 @@ export type RevoLockFile = {
144
144
  schedules: Record<string, ScheduleLockEntry>;
145
145
  events: Record<string, EventLockEntry>;
146
146
  endpoints: Record<string, EndpointLockEntry>;
147
+ applications: Record<string, EndpointLockEntry>;
147
148
  databaseSchemas: Record<string, DatabaseSchemaLockEntry>;
148
149
  databaseViews: Record<string, DatabaseViewLockEntry>;
149
150
  };
@@ -191,7 +192,7 @@ export type PortableComponentConfigField = (typeof PORTABLE_COMPONENT_CONFIG_FIE
191
192
  export declare function componentActivationValidationError(source: ComponentRecord): "Component active must be a boolean." | null;
192
193
  export declare function componentTypeTransitionReason(desired: string, current: string): string | null;
193
194
  export declare function diffPortableComponentSource(source: ComponentRecord, target: ComponentRecord): {
194
- configurationFields: ("name" | "metadata" | "category" | "desc" | "type" | "active" | "testConfig")[];
195
+ configurationFields: ("metadata" | "name" | "type" | "category" | "desc" | "active" | "testConfig")[];
195
196
  elementsChanged: boolean;
196
197
  changedFields: string[];
197
198
  };
@@ -224,6 +224,7 @@ export function readComponentLock(projectRoot) {
224
224
  schedules: {},
225
225
  events: {},
226
226
  endpoints: {},
227
+ applications: {},
227
228
  databaseSchemas: {},
228
229
  databaseViews: {},
229
230
  }, lockPath, null);
@@ -458,6 +459,25 @@ export function readComponentLock(projectRoot) {
458
459
  ...(baseline.omitBaseline ? { omitBaseline: baseline.omitBaseline } : {}),
459
460
  }])),
460
461
  }])),
462
+ applications: Object.fromEntries(Object.entries(raw.applications && typeof raw.applications === 'object' ? raw.applications : {})
463
+ .filter(([, entry]) => (typeof entry.stableKey === 'string'
464
+ && typeof entry.path === 'string'
465
+ && typeof entry.sourceHash === 'string'
466
+ && entry.environments
467
+ && typeof entry.environments === 'object'))
468
+ .map(([key, entry]) => [key, {
469
+ stableKey: String(entry.stableKey),
470
+ path: String(entry.path),
471
+ sourceHash: String(entry.sourceHash),
472
+ ...(entry.sourceBaseline ? { sourceBaseline: entry.sourceBaseline } : {}),
473
+ environments: Object.fromEntries(Object.entries(entry.environments)
474
+ .filter(([, baseline]) => typeof baseline.remoteHash === 'string' && typeof baseline.syncedAt === 'string')
475
+ .map(([envName, baseline]) => [envName, {
476
+ remoteHash: String(baseline.remoteHash),
477
+ syncedAt: String(baseline.syncedAt),
478
+ ...(baseline.omitBaseline ? { omitBaseline: baseline.omitBaseline } : {}),
479
+ }])),
480
+ }])),
461
481
  databaseSchemas: Object.fromEntries(Object.entries(raw.databaseSchemas && typeof raw.databaseSchemas === 'object' ? raw.databaseSchemas : {})
462
482
  .filter(([, entry]) => (typeof entry.stableKey === 'string'
463
483
  && typeof entry.path === 'string'
@@ -522,7 +542,7 @@ function writeComponentLockWithRevision(projectRoot, lock) {
522
542
  // Keep field digests beside each verified baseline, never input/secret values.
523
543
  const fields = [
524
544
  ['component', 'components'], ['database-table', 'databaseSchemas'], ['database-view', 'databaseViews'],
525
- ['job-template', 'jobTemplates'], ['endpoint', 'endpoints'], ['schedule', 'schedules'], ['event', 'events'],
545
+ ['job-template', 'jobTemplates'], ['endpoint', 'endpoints'], ['application', 'applications'], ['schedule', 'schedules'], ['event', 'events'],
526
546
  ['group', 'groups'], ['role-group', 'roleGroups'], ['service-account', 'serviceAccounts'],
527
547
  ['agent', 'agents'], ['agent-plugin', 'agentPlugins'],
528
548
  ];
@@ -580,6 +600,7 @@ function writeComponentLockWithRevision(projectRoot, lock) {
580
600
  ...(Object.keys(sortedSchedules).length > 0 ? { schedules: sortedSchedules } : {}),
581
601
  ...(Object.keys(sortedEvents).length > 0 ? { events: sortedEvents } : {}),
582
602
  ...(Object.keys(sortedEndpoints).length > 0 ? { endpoints: sortedEndpoints } : {}),
603
+ ...(Object.keys(lock.applications || {}).length ? { applications: Object.fromEntries(Object.entries(lock.applications).sort(([a], [b]) => a.localeCompare(b))) } : {}),
583
604
  ...(Object.keys(sortedDatabaseSchemas).length > 0 ? { databaseSchemas: sortedDatabaseSchemas } : {}),
584
605
  ...(Object.keys(sortedDatabaseViews).length > 0 ? { databaseViews: sortedDatabaseViews } : {}),
585
606
  });
@@ -0,0 +1,25 @@
1
+ import { type RevoClient } from './client.ts';
2
+ /** Stable system identity; named Applications are portable by their immutable key. */
3
+ export declare const DEFAULT_ENDPOINT_APPLICATION_ID = "00000000-0000-4000-8000-000000000001";
4
+ export declare const DEFAULT_ENDPOINT_APPLICATION_KEY = "@default";
5
+ export type EndpointApplicationReference = {
6
+ key: string;
7
+ } | {
8
+ system: '@default';
9
+ };
10
+ export type EndpointApplicationRecord = {
11
+ serviceId: string;
12
+ key: string;
13
+ system: boolean;
14
+ version: number;
15
+ name?: string;
16
+ description?: string | null;
17
+ cors?: unknown;
18
+ };
19
+ export declare function isNamedApplicationKey(value: unknown): value is string;
20
+ export declare function validEndpointApplication(value: unknown): value is EndpointApplicationReference | undefined;
21
+ export declare function endpointApplicationKey(reference?: EndpointApplicationReference): string;
22
+ export declare function listEndpointApplications(client: RevoClient): Promise<EndpointApplicationRecord[]>;
23
+ export declare function endpointRecordApplicationKey(record: Record<string, unknown>, applications?: EndpointApplicationRecord[]): string;
24
+ export declare function portableEndpointApplication(client: RevoClient, record: Record<string, unknown>, applications?: EndpointApplicationRecord[]): Promise<EndpointApplicationReference | undefined>;
25
+ export declare function resolveEndpointApplication(client: RevoClient, reference?: EndpointApplicationReference): Promise<EndpointApplicationRecord | undefined>;
@@ -0,0 +1,75 @@
1
+ import { ApiError } from "./client.js";
2
+ /** Stable system identity; named Applications are portable by their immutable key. */
3
+ export const DEFAULT_ENDPOINT_APPLICATION_ID = '00000000-0000-4000-8000-000000000001';
4
+ export const DEFAULT_ENDPOINT_APPLICATION_KEY = '@default';
5
+ export function isNamedApplicationKey(value) {
6
+ return typeof value === 'string' && value.length <= 63 && value !== 'default'
7
+ && /^(?=.{1,63}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?![\s\S])/.test(value);
8
+ }
9
+ export function validEndpointApplication(value) {
10
+ if (value === undefined)
11
+ return true;
12
+ if (!value || typeof value !== 'object' || Array.isArray(value))
13
+ return false;
14
+ const reference = value;
15
+ return Object.keys(reference).length === 1
16
+ && (reference.system === '@default' || isNamedApplicationKey(reference.key));
17
+ }
18
+ export function endpointApplicationKey(reference) {
19
+ if (!validEndpointApplication(reference))
20
+ throw new Error('Invalid portable Endpoint Application reference.');
21
+ return reference && 'key' in reference ? reference.key : DEFAULT_ENDPOINT_APPLICATION_KEY;
22
+ }
23
+ export async function listEndpointApplications(client) {
24
+ let applications;
25
+ try {
26
+ ({ applications } = await client.listAllApplications());
27
+ }
28
+ catch (error) {
29
+ if (error instanceof ApiError && error.status === 404)
30
+ throw new Error('The selected instance does not support the Applications catalog required by named Endpoint bindings.');
31
+ throw error;
32
+ }
33
+ const ids = new Set();
34
+ const keys = new Set();
35
+ for (const application of applications) {
36
+ if (typeof application.serviceId !== 'string' || !application.serviceId || typeof application.system !== 'boolean'
37
+ || typeof application.key !== 'string' || ids.has(application.serviceId) || keys.has(application.key)
38
+ || application.system !== (application.serviceId === DEFAULT_ENDPOINT_APPLICATION_ID)
39
+ || application.system !== (application.key === DEFAULT_ENDPOINT_APPLICATION_KEY)
40
+ || !application.system && !isNamedApplicationKey(application.key)
41
+ || !Number.isInteger(application.version) || application.version < 0) {
42
+ throw new Error('Application catalog has an invalid or ambiguous identity.');
43
+ }
44
+ ids.add(application.serviceId);
45
+ keys.add(application.key);
46
+ }
47
+ if (!keys.has(DEFAULT_ENDPOINT_APPLICATION_KEY))
48
+ throw new Error('Application catalog is incomplete: canonical system Default Application is missing.');
49
+ return applications;
50
+ }
51
+ export function endpointRecordApplicationKey(record, applications = []) {
52
+ if (record.serviceId === undefined || record.serviceId === DEFAULT_ENDPOINT_APPLICATION_ID)
53
+ return DEFAULT_ENDPOINT_APPLICATION_KEY;
54
+ const matches = applications.filter(application => application.serviceId === record.serviceId);
55
+ if (matches.length !== 1 || matches[0].system)
56
+ throw new Error('Endpoint Application is missing or ambiguous in the current catalog.');
57
+ return matches[0].key;
58
+ }
59
+ export async function portableEndpointApplication(client, record, applications) {
60
+ if (record.serviceId === undefined)
61
+ return undefined;
62
+ if (record.serviceId === DEFAULT_ENDPOINT_APPLICATION_ID)
63
+ return { system: '@default' };
64
+ const key = endpointRecordApplicationKey(record, applications ?? await listEndpointApplications(client));
65
+ return { key };
66
+ }
67
+ export async function resolveEndpointApplication(client, reference) {
68
+ const key = endpointApplicationKey(reference);
69
+ if (key === DEFAULT_ENDPOINT_APPLICATION_KEY)
70
+ return undefined;
71
+ const matches = (await listEndpointApplications(client)).filter(application => application.key === key && !application.system);
72
+ if (matches.length !== 1)
73
+ throw new Error(`Endpoint Application "${key}" is missing or ambiguous in the target.`);
74
+ return matches[0];
75
+ }
@@ -30,6 +30,7 @@ export type EndpointRequestEvent = {
30
30
  event: 'request_aborted';
31
31
  })));
32
32
  type LocalExecution = {
33
+ applicationKey?: string;
33
34
  workspaceRoot: string;
34
35
  stableKeyName: string;
35
36
  readOnly: boolean;
@@ -41,6 +42,10 @@ type EmulatorOptions = {
41
42
  onRequest?: (event: EndpointRequestEvent) => void;
42
43
  } & (LocalExecution | {
43
44
  runPublishedEndpoint: PublishedEndpoint;
45
+ preflightPublishedEndpoint?: (input: {
46
+ method: string;
47
+ url: URL;
48
+ }) => Promise<HttpResult | undefined>;
44
49
  });
45
50
  export declare function normalizeEmulatorHost(value: string): string;
46
51
  export declare function formatEmulatorHost(host: string): string;
@@ -8,6 +8,7 @@ import { componentContentDigest } from "./component-contract.js";
8
8
  import { buildDebugElements, normalizeComponentType } from "./component-debug-source.js";
9
9
  import { readConfiguredResourceMetadataStableKey } from "./resource-metadata.js";
10
10
  import { retiredLibraryOptionErrors } from "./request-contract.js";
11
+ import { DEFAULT_ENDPOINT_APPLICATION_KEY, endpointApplicationKey } from "./endpoint-application.js";
11
12
  import { ENDPOINT_MANIFEST_FILE, ENDPOINTS_DIRECTORY, validateEndpointManifest, } from "./resource-syncs/endpoint-sync.js";
12
13
  import { normalizeEndpointPath } from "./resource-syncs/runtime-definition-validation.js";
13
14
  import { isRecord } from "./resource-syncs/util.js";
@@ -96,6 +97,13 @@ async function matchRoute(options, method, pathname) {
96
97
  const files = await readManifests(path.join(options.workspaceRoot, ENDPOINTS_DIRECTORY), ENDPOINT_MANIFEST_FILE);
97
98
  const segments = normalizeEndpointPath(pathname).split('/');
98
99
  const matches = files.flatMap(({ value, file }) => {
100
+ try {
101
+ if (endpointApplicationKey(value.application) !== (options.applicationKey ?? DEFAULT_ENDPOINT_APPLICATION_KEY))
102
+ return [];
103
+ }
104
+ catch {
105
+ throw new EmulatorError(422, 'INVALID_ENDPOINT_APPLICATION', 'Invalid portable Endpoint Application reference.');
106
+ }
99
107
  if (value.active !== true || !isRecord(value.route) || value.route.method !== method
100
108
  || typeof value.route.path !== 'string')
101
109
  return [];
@@ -127,12 +135,30 @@ async function matchRoute(options, method, pathname) {
127
135
  const retired = retiredLibraryOptionErrors(match.value.options);
128
136
  if (retired.length)
129
137
  throw new EmulatorError(422, 'EXECUTION_LIBRARY_OPTION_REMOVED', retired.join('\n'));
138
+ if (isRecord(match.value.options)
139
+ && (match.value.options.requestBody != null || match.value.options.responseBody != null)) {
140
+ throw new EmulatorError(501, 'ENDPOINT_BODY_FORMAT_UNSUPPORTED', 'Local endpoint emulation does not implement options.requestBody or options.responseBody semantics. '
141
+ + 'Call the Endpoint runtime directly to validate explicit request and response formats.');
142
+ }
143
+ const applicationKey = options.applicationKey ?? DEFAULT_ENDPOINT_APPLICATION_KEY;
144
+ const applications = (await readManifests(path.join(options.workspaceRoot, 'Applications'), 'application.json'))
145
+ .filter(application => application.value.key === applicationKey);
146
+ if (applications.length > 1)
147
+ throw new EmulatorError(409, 'AMBIGUOUS_APPLICATION', 'More than one local Application has the selected key.');
148
+ const application = applications[0]?.value;
149
+ if (application?.anonymousAccess != null && (!isRecord(application.anonymousAccess) || typeof application.anonymousAccess.enabled !== 'boolean'))
150
+ throw new EmulatorError(422, 'INVALID_APPLICATION_ACCESS', 'Invalid local Application anonymous access policy.');
151
+ if (application?.invocationPolicy != null || isRecord(application?.anonymousAccess) && application.anonymousAccess.enabled === true) {
152
+ throw new EmulatorError(501, 'APPLICATION_ACCESS_POLICY_UNSUPPORTED', 'Local Sandbox preview cannot verify Application invocation ACLs, anonymous identity or shared anonymous limits. Use the real Endpoint runtime.');
153
+ }
130
154
  if (!validateEndpointManifest(match.value, options.stableKeyName)) {
131
155
  throw new EmulatorError(422, 'INVALID_ENDPOINT', `Invalid local endpoint: ${path.basename(path.dirname(match.file))}.`);
132
156
  }
133
157
  return { endpoint: match.value, parameters: match.parameters };
134
158
  }
135
159
  function assertSupportedEndpoint(endpoint) {
160
+ if (endpoint.allowUnauthenticated === true)
161
+ throw new EmulatorError(501, 'ENDPOINT_ANONYMOUS_ACCESS_UNSUPPORTED', 'Local Sandbox preview cannot verify anonymous Endpoint authority or rate limits. Use the real Endpoint runtime.');
136
162
  const options = endpoint.options ?? {};
137
163
  const policy = endpoint.executionPolicy;
138
164
  if (policy?.currentUser === 'EXECUTION_ACCOUNT' || (policy?.mode === 'SERVICE_ACCOUNT' && policy.currentUser !== 'CALLER')) {
@@ -298,6 +324,9 @@ async function executeRequest(emulator, request, signal, onRoute, onExecution) {
298
324
  const url = new URL(rawUrl, 'http://localhost');
299
325
  const method = request.method ?? 'GET';
300
326
  if ('runPublishedEndpoint' in emulator) {
327
+ const rejected = await emulator.preflightPublishedEndpoint?.({ method, url });
328
+ if (rejected)
329
+ return rejected;
301
330
  for (const name of [...url.searchParams.keys()]) {
302
331
  if (OMITTED_QUERY_PARAMETERS.has(name.toLowerCase()))
303
332
  url.searchParams.delete(name);
@@ -0,0 +1,2 @@
1
+ /** Storage directives require the matching native RUN transport, not JSON body emulation. */
2
+ export declare function usesEndpointStorageTransport(options: unknown): boolean;
@@ -0,0 +1,8 @@
1
+ /** Storage directives require the matching native RUN transport, not JSON body emulation. */
2
+ export function usesEndpointStorageTransport(options) {
3
+ if (!options || typeof options !== 'object' || Array.isArray(options))
4
+ return false;
5
+ const value = options;
6
+ return [value.requestBody, value.responseBody].some(body => body && typeof body === 'object' && !Array.isArray(body)
7
+ && body.mode === 'storage');
8
+ }