@shiqianjiang/ceru-plugin-cli 0.1.2 → 0.2.1

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 (70) hide show
  1. package/README.md +6 -6
  2. package/assets/core-contracts.js +1 -0
  3. package/assets/index.html +94 -93
  4. package/assets/playground.js +293 -30
  5. package/assets/sandbox.js +50 -19
  6. package/assets/style.css +16 -0
  7. package/dist/dependencies.d.ts +6 -0
  8. package/dist/dependencies.js +45 -0
  9. package/dist/dev.js +214 -119
  10. package/dist/index.js +5 -3
  11. package/dist/project.js +41 -16
  12. package/dist/socket-broker.d.ts +23 -0
  13. package/dist/socket-broker.js +230 -0
  14. package/package.json +71 -67
  15. package/schemas/config.schema.json +347 -0
  16. package/templates/connected-library/js/.vscode/ceru.code-snippets +37 -9
  17. package/templates/connected-library/js/package.json +2 -2
  18. package/templates/connected-library/js/src/index.js +7 -5
  19. package/templates/connected-library/ts/.vscode/ceru.code-snippets +37 -9
  20. package/templates/connected-library/ts/package.json +2 -2
  21. package/templates/connected-library/ts/src/index.ts +7 -5
  22. package/templates/guest-adapter/js/.vscode/ceru.code-snippets +37 -9
  23. package/templates/guest-adapter/js/package.json +2 -2
  24. package/templates/guest-adapter/ts/.vscode/ceru.code-snippets +37 -9
  25. package/templates/guest-adapter/ts/package.json +2 -2
  26. package/templates/importer/js/.vscode/ceru.code-snippets +37 -9
  27. package/templates/importer/js/README.md +1 -1
  28. package/templates/importer/js/ceru.plugin.json +8 -24
  29. package/templates/importer/js/package.json +2 -2
  30. package/templates/importer/js/src/index.js +28 -34
  31. package/templates/importer/ts/.vscode/ceru.code-snippets +37 -9
  32. package/templates/importer/ts/README.md +1 -1
  33. package/templates/importer/ts/ceru.plugin.json +8 -24
  34. package/templates/importer/ts/package.json +2 -2
  35. package/templates/importer/ts/src/index.ts +28 -34
  36. package/templates/react/js/.vscode/ceru.code-snippets +37 -9
  37. package/templates/react/js/package.json +2 -2
  38. package/templates/react/ts/.vscode/ceru.code-snippets +37 -9
  39. package/templates/react/ts/package.json +2 -2
  40. package/templates/snapshot.json +4 -2
  41. package/templates/source/js/.vscode/ceru.code-snippets +37 -9
  42. package/templates/source/js/ceru.plugin.json +9 -0
  43. package/templates/source/js/package.json +2 -2
  44. package/templates/source/js/src/index.js +29 -26
  45. package/templates/source/ts/.vscode/ceru.code-snippets +37 -9
  46. package/templates/source/ts/ceru.plugin.json +9 -0
  47. package/templates/source/ts/package.json +2 -2
  48. package/templates/source/ts/src/index.ts +29 -26
  49. package/templates/vue/js/.vscode/ceru.code-snippets +37 -9
  50. package/templates/vue/js/package.json +2 -2
  51. package/templates/vue/ts/.vscode/ceru.code-snippets +37 -9
  52. package/templates/vue/ts/package.json +2 -2
  53. package/templates/vue-tsx/js/.vscode/ceru.code-snippets +37 -9
  54. package/templates/vue-tsx/js/package.json +2 -2
  55. package/templates/vue-tsx/ts/.vscode/ceru.code-snippets +37 -9
  56. package/templates/vue-tsx/ts/package.json +2 -2
  57. package/templates/web-dist/js/.vscode/ceru.code-snippets +37 -9
  58. package/templates/web-dist/js/package.json +2 -2
  59. package/templates/web-dist/ts/.vscode/ceru.code-snippets +37 -9
  60. package/templates/web-dist/ts/package.json +2 -2
  61. package/templates/web-surface/js/.vscode/ceru.code-snippets +37 -9
  62. package/templates/web-surface/js/ceru.plugin.json +9 -0
  63. package/templates/web-surface/js/package.json +2 -2
  64. package/templates/web-surface/js/src/view.js +4 -1
  65. package/templates/web-surface/js/ui/search-note.css +3 -0
  66. package/templates/web-surface/ts/.vscode/ceru.code-snippets +37 -9
  67. package/templates/web-surface/ts/ceru.plugin.json +9 -0
  68. package/templates/web-surface/ts/package.json +2 -2
  69. package/templates/web-surface/ts/src/view.ts +4 -1
  70. package/templates/web-surface/ts/ui/search-note.css +3 -0
package/assets/style.css CHANGED
@@ -117,6 +117,15 @@ aside .item {
117
117
  gap: 8px;
118
118
  margin: 10px 0;
119
119
  }
120
+ .permission-group {
121
+ display: flex;
122
+ align-items: center;
123
+ justify-content: space-between;
124
+ gap: 8px;
125
+ margin: 16px 0 6px;
126
+ padding-top: 12px;
127
+ border-top: 1px solid var(--line);
128
+ }
120
129
  .hint {
121
130
  font-size: 12px;
122
131
  color: var(--muted);
@@ -192,6 +201,13 @@ pre {
192
201
  display: block;
193
202
  width: 100%;
194
203
  }
204
+ .host-content-preview {
205
+ margin: 12px 0;
206
+ padding: 24px;
207
+ border: 1px dashed var(--green);
208
+ border-radius: 8px;
209
+ color: var(--muted);
210
+ }
195
211
  .log-column {
196
212
  position: sticky;
197
213
  top: 16px;
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from 'esbuild';
2
+ export declare const HOST_MODULES: Set<string>;
3
+ /** Only explicitly named Host modules are replaced. All other packages go through esbuild. */
4
+ export declare function hostModulesPlugin(): Plugin;
5
+ /** Catch unresolved/dynamic CommonJS loading after bundling, including aliases. */
6
+ export declare function assertBundledDependencies(code: string): void;
@@ -0,0 +1,45 @@
1
+ import { parse } from 'acorn';
2
+ import { HOST_MODULE_NAMES } from '@shiqianjiang/ceru-plugin-sdk/catalog';
3
+ export const HOST_MODULES = new Set(HOST_MODULE_NAMES);
4
+ /** Only explicitly named Host modules are replaced. All other packages go through esbuild. */
5
+ export function hostModulesPlugin() {
6
+ return {
7
+ name: 'ceru-host-modules',
8
+ setup(build) {
9
+ build.onResolve({ filter: /^(?:ceru|@ceru\/[^/]+|lodash)$/ }, (args) => {
10
+ if (!HOST_MODULES.has(args.path))
11
+ return { errors: [{ text: 'Unknown Host module: ' + args.path }] };
12
+ return { path: args.path, namespace: 'ceru-host' };
13
+ });
14
+ build.onLoad({ filter: /.*/, namespace: 'ceru-host' }, (args) => ({
15
+ contents: 'module.exports = globalThis.__ceruRequire(' + JSON.stringify(args.path) + ')',
16
+ loader: 'js',
17
+ }));
18
+ },
19
+ };
20
+ }
21
+ /** Catch unresolved/dynamic CommonJS loading after bundling, including aliases. */
22
+ export function assertBundledDependencies(code) {
23
+ const tree = parse(code, { ecmaVersion: 2022, sourceType: 'script' });
24
+ const stack = [tree];
25
+ while (stack.length) {
26
+ const node = stack.pop();
27
+ if (node.type === 'ImportExpression')
28
+ throw new Error('Dynamic import remains in the output; use a static import');
29
+ if (node.type === 'CallExpression' &&
30
+ node.callee?.type === 'Identifier' &&
31
+ (node.callee.name === 'require' || /^__require\d*$/.test(node.callee.name)) &&
32
+ node.arguments.length) {
33
+ throw new Error('Unresolved require() remains in the output. Use a literal local/package import, or a documented Host module.');
34
+ }
35
+ for (const value of Object.values(node)) {
36
+ if (Array.isArray(value)) {
37
+ for (const child of value)
38
+ if (child?.type)
39
+ stack.push(child);
40
+ }
41
+ else if (value && typeof value === 'object' && 'type' in value)
42
+ stack.push(value);
43
+ }
44
+ }
45
+ }
package/dist/dev.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { readFile, realpath } from 'node:fs/promises';
2
2
  import { watch } from 'node:fs';
3
- import { createServer, request as httpRequest } from 'node:http';
4
- import { request as httpsRequest } from 'node:https';
3
+ import { createServer, Agent as HttpAgent } from 'node:http';
4
+ import { Agent as HttpsAgent } from 'node:https';
5
+ import axios from 'axios';
6
+ import { SocketBroker } from './socket-broker.js';
5
7
  import { lookup } from 'node:dns/promises';
6
8
  import { isIP } from 'node:net';
7
9
  import { resolve, relative, dirname } from 'node:path';
@@ -36,17 +38,20 @@ async function waitForDebugger(origin, port, exited) {
36
38
  }
37
39
  const privateAddress = (address) => {
38
40
  const value = address.toLowerCase();
41
+ if (value.startsWith('::ffff:'))
42
+ return privateAddress(value.slice('::ffff:'.length));
39
43
  if (value.includes(':'))
40
44
  return (value === '::1' ||
41
45
  value.startsWith('fc') ||
42
46
  value.startsWith('fd') ||
43
- value.startsWith('fe80') ||
44
- value.startsWith('::ffff:'));
47
+ value.startsWith('fe80'));
45
48
  const p = value.split('.').map(Number);
46
49
  return (p[0] === 0 ||
47
50
  p[0] === 10 ||
48
51
  p[0] === 127 ||
49
- p[0] === 169 ||
52
+ (p[0] === 169 && p[1] === 254) ||
53
+ (p[0] === 100 && p[1] >= 64 && p[1] <= 127) ||
54
+ (p[0] === 198 && (p[1] === 18 || p[1] === 19)) ||
50
55
  p[0] >= 224 ||
51
56
  (p[0] === 172 && p[1] >= 16 && p[1] <= 31) ||
52
57
  (p[0] === 192 && p[1] === 168));
@@ -62,22 +67,7 @@ async function bodyJson(request) {
62
67
  }
63
68
  return parseJsonStrict(Buffer.concat(chunks).toString('utf8'));
64
69
  }
65
- /** Narrow development broker: exact granted origin, no redirects, pinned DNS, bounded response. */
66
- async function fetchAllowed(input, permission, privateAllowed, binary = false, reservedPorts = []) {
67
- const url = new URL(input.url);
68
- if (url.username || url.password || !['http:', 'https:'].includes(url.protocol))
69
- throw new Error('Unsupported URL');
70
- if (url.origin !== permission.origin)
71
- throw new Error('Origin is not granted: ' + url.origin);
72
- if (url.protocol === 'http:' && !privateAllowed)
73
- throw new Error('HTTP requires a separately granted network.private permission');
74
- const method = String(input.method ?? 'GET').toUpperCase();
75
- if (!permission.methods.includes(method))
76
- throw new Error('Method is outside the declared scope');
77
- if (/%(?:2f|5c)/i.test(url.pathname))
78
- throw new Error('Encoded path separator is not supported');
79
- if (!permission.paths.some((path) => url.pathname === path || url.pathname.startsWith(path.endsWith('/') ? path : path + '/')))
80
- throw new Error('Path is outside the declared scope');
70
+ async function allowedAddress(url, privateAllowed, reservedPorts) {
81
71
  const hostname = url.hostname.replace(/^\[|\]$/g, '');
82
72
  const addresses = isIP(hostname)
83
73
  ? [{ address: hostname, family: isIP(hostname) }]
@@ -86,15 +76,20 @@ async function fetchAllowed(input, permission, privateAllowed, binary = false, r
86
76
  throw new Error('No address found');
87
77
  for (const { address } of addresses) {
88
78
  if ((address.startsWith('127.') || address === '::1') &&
89
- reservedPorts.includes(Number(url.port) || (url.protocol === 'https:' ? 443 : 80))) {
79
+ reservedPorts.includes(Number(url.port) || (url.protocol === 'https:' ? 443 : 80)))
90
80
  throw new Error('Development Host and debugger endpoints are reserved');
91
- }
92
- if (/^(169\.254\.|fe80:|::ffff:)/i.test(address))
93
- throw new Error('Sensitive/link-local address is blocked');
94
81
  if (privateAddress(address) && !privateAllowed)
95
82
  throw new Error('Private network access is not granted');
96
83
  }
97
- const chosen = addresses[0];
84
+ return addresses[0];
85
+ }
86
+ /** Development broker: capability-gated network, private-network split, pinned DNS, bounded response. */
87
+ async function fetchAllowed(input, privateAllowed, reservedPorts = [], signal, redirects = 0) {
88
+ const url = new URL(input.url);
89
+ if (!['http:', 'https:'].includes(url.protocol))
90
+ throw new Error('Unsupported URL');
91
+ const method = String(input.method ?? 'GET').toUpperCase();
92
+ const chosen = await allowedAddress(url, privateAllowed, reservedPorts);
98
93
  const headers = { 'Accept-Encoding': 'identity' };
99
94
  for (const [name, value] of Object.entries(input.headers ?? {})) {
100
95
  if (/^(host|connection|content-length|transfer-encoding|accept-encoding|proxy-.*|upgrade)$/i.test(name))
@@ -106,47 +101,61 @@ async function fetchAllowed(input, permission, privateAllowed, binary = false, r
106
101
  if (input.body !== undefined &&
107
102
  (typeof input.body !== 'string' || Buffer.byteLength(input.body) > 1024 * 1024))
108
103
  throw new Error('Invalid request body');
109
- return new Promise((resolveResponse, reject) => {
110
- const request = (url.protocol === 'https:' ? httpsRequest : httpRequest)(url, {
104
+ const pinLookup = ((_host, options, callback) => options?.all ? callback(null, [chosen]) : callback(null, chosen.address, chosen.family));
105
+ const httpAgent = new HttpAgent({ lookup: pinLookup });
106
+ const httpsAgent = new HttpsAgent({ lookup: pinLookup });
107
+ try {
108
+ const response = await axios.request({
109
+ url: url.href,
111
110
  method,
112
111
  headers,
113
- lookup: ((_host, options, callback) => options?.all
114
- ? callback(null, [chosen])
115
- : callback(null, chosen.address, chosen.family)),
116
- }, (response) => {
117
- const chunks = [];
118
- let total = 0;
119
- response.on('data', (chunk) => {
120
- total += chunk.length;
121
- if (total > (binary ? 32 : 2) * 1024 * 1024) {
122
- request.destroy(new Error('Response exceeds development limit'));
123
- return;
124
- }
125
- chunks.push(chunk);
126
- });
127
- response.once('error', reject);
128
- response.once('end', () => {
129
- if (binary) {
130
- resolveResponse({
131
- status: response.statusCode,
132
- headers: response.headers,
133
- bytes: Buffer.concat(chunks),
134
- });
135
- return;
136
- }
137
- const text = Buffer.concat(chunks).toString('utf8');
138
- let body = text;
139
- try {
140
- body = JSON.parse(text);
141
- }
142
- catch { }
143
- resolveResponse({ status: response.statusCode, headers: response.headers, body });
144
- });
112
+ data: input.body,
113
+ adapter: 'http',
114
+ httpAgent,
115
+ httpsAgent,
116
+ proxy: false,
117
+ maxRedirects: 0,
118
+ timeout: Math.max(1000, Math.min(30000, Number(input.timeoutMs) || 15000)),
119
+ maxContentLength: 2 * 1024 * 1024,
120
+ maxBodyLength: 1024 * 1024,
121
+ responseType: 'arraybuffer',
122
+ validateStatus: () => true,
123
+ transformResponse: [(data) => data],
124
+ signal,
145
125
  });
146
- request.setTimeout(15000, () => request.destroy(new Error('HTTP timeout')));
147
- request.once('error', reject);
148
- request.end(input.body);
149
- });
126
+ const bytes = Buffer.from(response.data);
127
+ const responseHeaders = Object.fromEntries(Object.entries(response.headers).filter(([, value]) => value != null && typeof value !== 'function'));
128
+ if (response.status >= 300 &&
129
+ response.status < 400 &&
130
+ typeof responseHeaders.location === 'string') {
131
+ if (redirects >= 5)
132
+ throw new Error('HTTP redirect limit exceeded');
133
+ const nextMethod = response.status === 303 ? 'GET' : method;
134
+ return fetchAllowed({
135
+ ...input,
136
+ url: new URL(responseHeaders.location, url).href,
137
+ method: nextMethod,
138
+ ...(nextMethod === 'GET' ? { body: undefined } : {}),
139
+ }, privateAllowed, reservedPorts, signal, redirects + 1);
140
+ }
141
+ const text = bytes.toString('utf8');
142
+ let body = text;
143
+ try {
144
+ body = JSON.parse(text);
145
+ }
146
+ catch { }
147
+ return { status: response.status, headers: responseHeaders, body };
148
+ }
149
+ catch (error) {
150
+ // AxiosError includes config/headers: never send it through plugin logs or RPC.
151
+ throw new Error(axios.isAxiosError(error)
152
+ ? 'HTTP request failed (' + (error.code || 'NETWORK_ERROR') + ')'
153
+ : 'HTTP request failed');
154
+ }
155
+ finally {
156
+ httpAgent.destroy();
157
+ httpsAgent.destroy();
158
+ }
150
159
  }
151
160
  export async function runDev(project, options = {}) {
152
161
  const root = await realpath(resolve(project));
@@ -183,7 +192,7 @@ export async function runDev(project, options = {}) {
183
192
  const bytes = await readFile(path);
184
193
  const parsed = readArtifact(bytes);
185
194
  if (Object.keys(parsed.header.manifest.engines.libraries ?? {}).length)
186
- throw new Error('This artifact still requires Host frameworks. Rebuild it with CLI 0.1.2 or later.');
195
+ throw new Error('This artifact still requires Host frameworks. Rebuild it with CLI 0.2.0 or later.');
187
196
  // Serve the verified release functions as scripts inside the same isolated
188
197
  // Surface. No project imports, transpiler, or framework is involved here.
189
198
  const devModules = Object.fromEntries(Object.entries(parsed.modules).map(([id, code]) => [
@@ -203,9 +212,18 @@ export async function runDev(project, options = {}) {
203
212
  const nonce = randomBytes(24).toString('base64');
204
213
  const catalog = JSON.parse(await readFile(asset('catalog.json'), 'utf8'));
205
214
  let config = {};
215
+ try {
216
+ const configPath = resolve(root, '.ceru-dev/config.json');
217
+ config = parseJsonStrict(await readFile(configPath, 'utf8'));
218
+ }
219
+ catch (error) {
220
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT')
221
+ throw error;
222
+ }
206
223
  const grants = new Map();
224
+ const sockets = new SocketBroker();
225
+ const operations = new Map();
207
226
  const storage = new Map();
208
- const leases = new Map();
209
227
  const rebuild = async () => {
210
228
  if (running) {
211
229
  dirty = true;
@@ -219,8 +237,11 @@ export async function runDev(project, options = {}) {
219
237
  artifact = readArtifact(await readFile(build.path));
220
238
  revision++;
221
239
  error = null;
240
+ sockets.closeAll();
241
+ for (const operation of operations.values())
242
+ operation.abort();
243
+ operations.clear();
222
244
  grants.clear();
223
- leases.clear();
224
245
  console.log('Reloaded plugin revision ' + revision);
225
246
  }
226
247
  catch (e) {
@@ -277,28 +298,6 @@ export async function runDev(project, options = {}) {
277
298
  });
278
299
  return;
279
300
  }
280
- if (url.pathname.startsWith('/media/') && request.method === 'GET') {
281
- const lease = leases.get(url.pathname.slice('/media/'.length));
282
- const grant = lease && grants.get(lease.permissionKey);
283
- if (!lease || !grant || lease.expiresAt < Date.now())
284
- throw new Error('Media lease expired or revoked');
285
- const privateAllowed = artifact.header.manifest.permissions?.some((p) => p.name === 'network.private' && grants.get(p.key)?.origin === grant.origin) ?? false;
286
- const media = await fetchAllowed({
287
- url: lease.url,
288
- headers: request.headers.range ? { Range: request.headers.range } : {},
289
- }, grant, privateAllowed, true, [Number(new URL(origin).port), debugPort]);
290
- response.writeHead(media.status, {
291
- 'Content-Type': media.headers['content-type'] || 'application/octet-stream',
292
- 'Cache-Control': 'no-store',
293
- 'Content-Length': media.bytes.length,
294
- ...(media.headers['content-range']
295
- ? { 'Content-Range': media.headers['content-range'] }
296
- : {}),
297
- 'X-Content-Type-Options': 'nosniff',
298
- });
299
- response.end(media.bytes);
300
- return;
301
- }
302
301
  if (url.pathname === '/plugin.js' && ['GET', 'HEAD'].includes(request.method ?? '')) {
303
302
  if (error) {
304
303
  json(503, { error });
@@ -320,11 +319,16 @@ export async function runDev(project, options = {}) {
320
319
  json(403, { error: 'Invalid development session' });
321
320
  return;
322
321
  }
322
+ if (url.pathname === '/api/socket-events' && request.method === 'GET') {
323
+ json(200, { events: sockets.drain() });
324
+ return;
325
+ }
323
326
  if (url.pathname === '/api/state' && request.method === 'GET') {
324
327
  json(200, {
325
328
  revision,
326
329
  error,
327
330
  manifest: artifact.header.manifest,
331
+ migrationWarnings: artifact.migrationWarnings,
328
332
  resources: artifact.resources,
329
333
  catalog,
330
334
  config,
@@ -348,25 +352,62 @@ export async function runDev(project, options = {}) {
348
352
  const declaration = artifact.header.manifest.permissions?.find((p) => p.key === input.key);
349
353
  if (!declaration)
350
354
  throw new Error('Permission was not declared');
351
- if (!input.allow)
355
+ if (!input.allow) {
352
356
  grants.delete(input.key);
357
+ sockets.revoke(input.key);
358
+ }
353
359
  else {
354
- const scope = declaration.scope ?? {};
355
- const declaredOrigin = scope.origin;
356
- const chosen = typeof declaredOrigin === 'string' ? declaredOrigin : input.origin;
357
- if (declaration.name.startsWith('network.') && !chosen)
358
- throw new Error('Specify an exact origin');
359
- grants.set(input.key, {
360
- origin: chosen ? new URL(chosen).origin : '',
361
- methods: Array.isArray(scope.methods) ? scope.methods : ['GET', 'POST'],
362
- paths: Array.isArray(scope.pathPrefixes) ? scope.pathPrefixes : ['/'],
363
- });
360
+ grants.set(input.key, { name: declaration.name });
364
361
  }
365
362
  json(200, { ok: true });
366
363
  return;
367
364
  }
368
365
  if (url.pathname === '/api/rpc') {
369
366
  const data = input.data ?? {};
367
+ if (input.method.startsWith('sockets.')) {
368
+ if (input.method === 'sockets.closeAll') {
369
+ sockets.closeAll();
370
+ json(200, { value: null });
371
+ return;
372
+ }
373
+ if (input.method === 'sockets.connect') {
374
+ const declaration = artifact.header.manifest.permissions?.find((p) => p.key === data.permissionKey && p.name === 'network.socket');
375
+ const grant = declaration && grants.get(declaration.key);
376
+ if (!grant)
377
+ throw new Error('Socket permission is not granted');
378
+ const privateAllowed = artifact.header.manifest.permissions?.some((permission) => permission.name === 'network.private' && grants.has(permission.key)) ?? false;
379
+ const value = await sockets.connect(data, privateAllowed, [
380
+ Number(new URL(origin).port),
381
+ debugPort,
382
+ ]);
383
+ // A pending handshake must not outlive a revoked grant or plugin reload.
384
+ if (grants.get(declaration.key) !== grant) {
385
+ sockets.disconnect(value.id);
386
+ throw new Error('Socket permission was revoked');
387
+ }
388
+ json(200, { value });
389
+ return;
390
+ }
391
+ if (input.method === 'sockets.send') {
392
+ sockets.send(data.id, data.event, data.data);
393
+ json(200, { value: null });
394
+ return;
395
+ }
396
+ if (input.method === 'sockets.disconnect') {
397
+ sockets.disconnect(data.id);
398
+ json(200, { value: null });
399
+ return;
400
+ }
401
+ throw new Error('Unknown socket method');
402
+ }
403
+ if (input.method === 'operations.cancel') {
404
+ operations.get(String(data.id))?.abort();
405
+ json(200, { value: null });
406
+ return;
407
+ }
408
+ if (input.method.startsWith('library.playlists.')) {
409
+ throw new Error('此独立开发 Host 尚未连接澜音的歌单服务。本地歌单和云歌单由澜音管理;请在正式 Host 中调用此能力。开发环境不会创建替代歌单库。');
410
+ }
370
411
  if (input.method === 'config.get') {
371
412
  json(200, { value: config });
372
413
  return;
@@ -397,18 +438,61 @@ export async function runDev(project, options = {}) {
397
438
  });
398
439
  return;
399
440
  }
400
- if (input.method === 'media.createLease') {
401
- const declaration = artifact.header.manifest.permissions?.find((p) => p.key === data.permissionKey && p.name === 'network.request');
402
- const grant = declaration && grants.get(declaration.key);
403
- if (!grant || new URL(data.url).origin !== grant.origin)
404
- throw new Error('Media origin is not granted');
405
- const id = randomBytes(18).toString('hex');
406
- leases.set(id, {
407
- url: data.url,
408
- permissionKey: data.permissionKey,
409
- expiresAt: Math.min(Number(data.expiresAt) || Date.now() + 60000, Date.now() + 60000),
441
+ if (input.method === 'permissions.getGranted') {
442
+ json(200, {
443
+ value: (artifact.header.manifest.permissions ?? [])
444
+ .filter((permission) => grants.has(permission.key))
445
+ .map((permission) => ({
446
+ key: permission.key,
447
+ name: permission.name,
448
+ scope: permission.scope ?? {},
449
+ status: 'granted',
450
+ })),
451
+ });
452
+ return;
453
+ }
454
+ if (input.method === 'services.capabilities.list') {
455
+ json(200, {
456
+ value: [
457
+ 'account',
458
+ 'library',
459
+ 'player',
460
+ 'queue',
461
+ 'favorites',
462
+ 'history',
463
+ 'downloads',
464
+ 'files',
465
+ 'clipboard',
466
+ 'localMusic',
467
+ 'settings',
468
+ 'window',
469
+ 'hotkeys',
470
+ 'sharing',
471
+ 'rooms',
472
+ 'devices',
473
+ 'ai',
474
+ 'tasks',
475
+ ].map((service) => ({
476
+ service,
477
+ version: '1.0.0',
478
+ available: false,
479
+ reason: 'host-not-connected',
480
+ permissionGroups: [],
481
+ })),
482
+ });
483
+ return;
484
+ }
485
+ if (input.method === 'services.capabilities.get') {
486
+ const service = String(data.args?.[0] ?? '');
487
+ json(200, {
488
+ value: {
489
+ service,
490
+ version: '1.0.0',
491
+ available: false,
492
+ reason: 'host-not-connected',
493
+ permissionGroups: [],
494
+ },
410
495
  });
411
- json(200, { value: { kind: 'media', id } });
412
496
  return;
413
497
  }
414
498
  if (input.method === 'http.request') {
@@ -416,13 +500,20 @@ export async function runDev(project, options = {}) {
416
500
  const grant = declaration && grants.get(declaration.key);
417
501
  if (!grant)
418
502
  throw new Error('Network permission is not granted');
419
- const hasPrivate = artifact.header.manifest.permissions?.some((p) => p.name === 'network.private' && grants.get(p.key)?.origin === grant.origin) ?? false;
420
- json(200, {
421
- value: await fetchAllowed(data, grant, hasPrivate, false, [
422
- Number(new URL(origin).port),
423
- debugPort,
424
- ]),
425
- });
503
+ const hasPrivate = artifact.header.manifest.permissions?.some((permission) => permission.name === 'network.private' && grants.has(permission.key)) ?? false;
504
+ const operationId = String(data.operation?.id ?? '');
505
+ const controller = new AbortController();
506
+ if (operationId)
507
+ operations.set(operationId, controller);
508
+ try {
509
+ json(200, {
510
+ value: await fetchAllowed(data, hasPrivate, [Number(new URL(origin).port), debugPort], controller.signal),
511
+ });
512
+ }
513
+ finally {
514
+ if (operations.get(operationId) === controller)
515
+ operations.delete(operationId);
516
+ }
426
517
  return;
427
518
  }
428
519
  throw new Error('Development Host does not implement ' +
@@ -445,7 +536,7 @@ export async function runDev(project, options = {}) {
445
536
  type = 'text/html';
446
537
  response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'nonce-" +
447
538
  nonce +
448
- "'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; object-src 'none'");
539
+ "'; style-src 'self'; img-src 'self' data:; media-src 'self' http: https: data: blob:; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; object-src 'none'");
449
540
  }
450
541
  else if (url.pathname === '/sandbox.html') {
451
542
  const moduleId = url.searchParams.get('module') ?? '';
@@ -475,6 +566,7 @@ export async function runDev(project, options = {}) {
475
566
  else {
476
567
  const file = {
477
568
  '/playground.js': 'playground.js',
569
+ '/core-contracts.js': 'core-contracts.js',
478
570
  '/style.css': 'style.css',
479
571
  '/sandbox.js': 'sandbox.js',
480
572
  }[url.pathname];
@@ -514,6 +606,9 @@ export async function runDev(project, options = {}) {
514
606
  const address = server.address();
515
607
  origin = 'http://127.0.0.1:' + (typeof address === 'object' && address ? address.port : port);
516
608
  const close = () => {
609
+ sockets.closeAll();
610
+ for (const operation of operations.values())
611
+ operation.abort();
517
612
  clearTimeout(timer);
518
613
  watcher.close();
519
614
  electron?.kill();
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { createTemplate, generateSigningKeys, parseJsonStrict, PreparedIssuer, r
6
6
  import { buildProject, scaffoldProject, TEMPLATES, writeAtomic } from './project.js';
7
7
  import { runDev } from './dev.js';
8
8
  export { buildProject, loadProject, scaffoldProject, TEMPLATES } from './project.js';
9
- const VERSION = '0.1.2';
9
+ const VERSION = '0.2.1';
10
10
  const HELP = 'Ceru Plugin CLI ' +
11
11
  VERSION +
12
12
  '\n\n' +
@@ -25,8 +25,8 @@ const HELP = 'Ceru Plugin CLI ' +
25
25
  'TypeScript is type-checked before build. Final output is one .js file.\n' +
26
26
  'v2 Host integration is required. Validation does not execute or sandbox plugin code.\n';
27
27
  async function jsOutput(path, bytes, force) {
28
- if (!['.js', '.jsx'].includes(extname(path)))
29
- throw new Error('Output must be .js or .jsx containing compiled JavaScript');
28
+ if (extname(path) !== '.js')
29
+ throw new Error('Output must be .js containing compiled JavaScript');
30
30
  await writeAtomic(resolve(path), bytes, force);
31
31
  console.log('Wrote ' + resolve(path) + ' (' + bytes.length + ' bytes)');
32
32
  }
@@ -172,6 +172,8 @@ export async function runCli(argv = process.argv.slice(2)) {
172
172
  bytes: bytes.length,
173
173
  modules: Object.keys(result.modules),
174
174
  resources: Object.keys(result.resources),
175
+ sourceFormat: result.sourceFormat,
176
+ migrationWarnings: result.migrationWarnings,
175
177
  signature: result.signatureStatus,
176
178
  codeDigest: result.codeDigest,
177
179
  templateDigest: result.templateDigest,