@mearl/preset 0.0.0-stage → 3.0.0-beta.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @mearl/preset
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 浏览器包的准备与本地存储见 [能力包](../../docs/browser-bundles.md),整套原子激活与 App 实现映射见 [浏览器 Preset](../../docs/browser-presets.md)。这两类能力通过 `@mearl/preset/bundles` 导出。
4
+
5
+ 浏览器和 Node 共用一次继承解析及资源下载,见 [整套资源准备](../../docs/preset-preparation.md)。`preparePreset` 返回完整确切图与兼容的浏览器投影;Node 模块选择直接复用同批字节,准备过程不执行代码或安装外部环境。
6
+
7
+ 主入口在浏览器和 Node 中共享 preset 清单校验与继承解析,没有文件系统、网络、凭据或浏览器权限副作用;清单加载由调用方提供。可选子入口 `@mearl/preset/bundles` 提供资源校验、受限下载和显式调用的浏览器本地存储,见 [能力包说明](../../docs/browser-bundles.md)。
8
+
9
+ ```ts
10
+ import { resolvePreset, mergePresetDefaults } from '@mearl/preset';
11
+
12
+ const preset = await resolvePreset('https://example.com/presets/team.json', {
13
+ mearlApiVersion: '1.0.0',
14
+ async load(source) {
15
+ const response = await fetch(source);
16
+ if (!response.ok) throw new Error(`Preset load failed: ${response.status}`);
17
+ return response.json();
18
+ },
19
+ });
20
+
21
+ const effectiveSettings = mergePresetDefaults(preset.defaults, userSettings);
22
+ ```
23
+
24
+ 加载器负责检查来源、响应大小、重定向、认证和取消请求;上例仅演示合同。浏览器加载器应根据产品来源策略限制 URL,解析器不会把 HTTP(S)/file 形式的 URL 自动视为可信。
25
+
26
+ Node 模块快照与宿主加载合同见 [Node 能力包](../../docs/node-capabilities.md)。
27
+
28
+ ## 清单
29
+
30
+ ```json
31
+ {
32
+ "schemaVersion": 1,
33
+ "id": "team",
34
+ "version": "1.0.0",
35
+ "extends": { "source": "../base/preset.json", "version": "^1" },
36
+ "requires": { "mearlApi": "^1" },
37
+ "packages": {
38
+ "capture": { "source": "./capture/package.json", "runtimes": ["browser"] },
39
+ "unused": { "enabled": false }
40
+ },
41
+ "skills": {},
42
+ "providers": {},
43
+ "defaults": { "simulation": { "app": "sample" } },
44
+ "permissions": { "origins": ["https://*.example.com/*"] }
45
+ }
46
+ ```
47
+
48
+ - 单继承,最多 32 层;拒绝循环和不满足的父版本/API 要求。`version` 是确切 semver,组件 `version` 是版本要求,具体安装版本留给安装器解析。
49
+ - packages、skills、providers 按 ID 合并,子级字段覆盖同 ID 声明;数组整体替换。启用项最终必须存在 source,`enabled:false` 保留停用声明。
50
+ - 组件 `dependsOn` 引用同类组件 ID;检查最终继承图中的缺失、停用和循环依赖。它不表示 runtime 兼容或安装已完成。
51
+ - source 相对声明它的清单解析;子级只修改版本时不会改变继承 source 的基准 URL。
52
+ - defaults 递归合并对象,数组、标量和 null 替换;用户覆盖单独保存,在解析结果上应用。
53
+ - 权限汇总去重,结果仅表示需求;必须由浏览器安装器另行取得实际授权。
54
+ - appProfiles 是 App ID 到实现标识的覆盖映射。具体档案是否存在、所需包是否可执行,由后续能力目录校验,解析器不宣称已验证模拟效果。
55
+ - 结果保留父级到子级的确切版本链和各组件最近声明来源,加载失败不会生成部分成功的结果。
56
+ - 拒绝未知字段、非 JSON 配置和原型污染键。清单总量不超过 256 Ki UTF-16 code units,defaults 最大嵌套 32 层。
57
+
58
+ 本包尚不包含完整 preset 安装器、preset 锁文件持久化或 UI。浏览器宿主和 setup 需要复用同一解析结果接续资源准备、权限、注册与激活;能力包本地存储只负责已校验快照的事务替换。
@@ -0,0 +1,22 @@
1
+ import type { PreparedBundle } from './bundle.js';
2
+ import type { PresetManifest, ResolvedPreset } from './types.js';
3
+ import { type PreparePresetOptions, type PresetGraphSnapshot } from './prepare.js';
4
+ /** Core browser defaults also need synchronization when no browser package is declared. */
5
+ export declare function presetRequiresBrowser(preset: ResolvedPreset): boolean;
6
+ /** Exact manifests allow offline resolution without trusting a second serialized resolved graph. */
7
+ export type BrowserPresetSnapshot = PresetGraphSnapshot;
8
+ export interface PreparedBrowserPreset {
9
+ snapshot: BrowserPresetSnapshot;
10
+ preset: ResolvedPreset;
11
+ bundles: PreparedBundle[];
12
+ }
13
+ /** Browser selection can be derived from the same accepted batch without another download. */
14
+ export declare function browserPresetSnapshot(source: string, manifests: Record<string, PresetManifest>, preset: ResolvedPreset, bundles: PreparedBundle[]): Promise<PreparedBrowserPreset>;
15
+ export declare function prepareBrowserPreset(source: string, options: PreparePresetOptions): Promise<PreparedBrowserPreset>;
16
+ /** Verifies an independent copy before any asynchronous work can observe caller mutations. */
17
+ export declare function verifyBrowserPreset(value: BrowserPresetSnapshot, mearlApiVersion: string): Promise<{
18
+ snapshot: BrowserPresetSnapshot;
19
+ preset: ResolvedPreset;
20
+ }>;
21
+ /** Captures the supplied browser batch without fetching its mutable sources again. */
22
+ export declare function verifyPreparedBrowserPreset(value: Pick<PreparedBrowserPreset, 'snapshot' | 'bundles'>, mearlApiVersion: string): Promise<PreparedBrowserPreset>;
@@ -0,0 +1,52 @@
1
+ import { BundleError, MAX_BROWSER_STORAGE_BYTES, verifyBundle } from './bundle.js';
2
+ import { satisfies } from 'semver';
3
+ import { preparePresetPackages, presetPackages, presetSnapshotRevision, verifyPresetGraph } from './prepare.js';
4
+ /** Core browser defaults also need synchronization when no browser package is declared. */
5
+ export function presetRequiresBrowser(preset) {
6
+ return Object.values(preset.packages).some(entry => entry.enabled !== false && entry.runtimes?.includes('browser')) || Object.keys(preset.appProfiles).length > 0 || Object.keys(preset.defaults).some(key => key === 'simulation' || key === 'extension' || key === 'services');
7
+ }
8
+ /** Browser selection can be derived from the same accepted batch without another download. */
9
+ export async function browserPresetSnapshot(source, manifests, preset, bundles) {
10
+ const ids = new Set(presetPackages(preset, ['browser']).map(([id]) => id));
11
+ const selected = bundles.filter(bundle => ids.has(bundle.manifest.id));
12
+ const data = { source, manifests, bundleRevisions: Object.fromEntries(selected.map(bundle => [bundle.manifest.id, bundle.revision])) };
13
+ return { snapshot: { ...data, revision: await presetSnapshotRevision(data) }, preset, bundles: selected };
14
+ }
15
+ export async function prepareBrowserPreset(source, options) {
16
+ const prepared = await preparePresetPackages(source, options, ['browser']);
17
+ return browserPresetSnapshot(prepared.source, prepared.manifests, prepared.preset, prepared.bundles);
18
+ }
19
+ /** Verifies an independent copy before any asynchronous work can observe caller mutations. */
20
+ export async function verifyBrowserPreset(value, mearlApiVersion) {
21
+ return verifyPresetGraph(value, mearlApiVersion, ['browser'], false);
22
+ }
23
+ /** Captures the supplied browser batch without fetching its mutable sources again. */
24
+ export async function verifyPreparedBrowserPreset(value, mearlApiVersion) {
25
+ if (!Array.isArray(value.bundles) || value.bundles.length > 64)
26
+ throw new BundleError('BUNDLE_QUOTA', 'Browser preset package count exceeds 64');
27
+ let total = 0;
28
+ for (const bundle of value.bundles) {
29
+ if (!bundle?.resources || typeof bundle.resources !== 'object' || Array.isArray(bundle.resources))
30
+ throw new BundleError('BUNDLE_INVALID', 'Expected package resource buffers');
31
+ const resources = Object.values(bundle.resources);
32
+ if (resources.length > 64)
33
+ throw new BundleError('BUNDLE_QUOTA', 'Browser package resource count exceeds 64');
34
+ for (const bytes of resources) {
35
+ if (!(bytes instanceof Uint8Array))
36
+ throw new BundleError('BUNDLE_INVALID', 'Expected package resource buffers');
37
+ total += bytes.byteLength;
38
+ if (total > MAX_BROWSER_STORAGE_BYTES)
39
+ throw new BundleError('BUNDLE_QUOTA', 'Browser packages exceed the storage budget');
40
+ }
41
+ }
42
+ const [graph, bundles] = await Promise.all([
43
+ verifyBrowserPreset(value.snapshot, mearlApiVersion),
44
+ Promise.all(value.bundles.map(bundle => verifyBundle(bundle, mearlApiVersion))),
45
+ ]);
46
+ if (bundles.length !== Object.keys(graph.snapshot.bundleRevisions).length || new Set(bundles.map(bundle => bundle.manifest.id)).size !== bundles.length || bundles.some(bundle => {
47
+ const entry = graph.preset.packages[bundle.manifest.id];
48
+ return graph.snapshot.bundleRevisions[bundle.manifest.id] !== bundle.revision || entry?.source !== bundle.source || (entry.version && !satisfies(bundle.manifest.version, entry.version));
49
+ }))
50
+ throw new BundleError('BUNDLE_INTEGRITY', 'Browser activation requires every exact package');
51
+ return { ...graph, bundles };
52
+ }
@@ -0,0 +1,47 @@
1
+ import type { JsonObject } from './types.js';
2
+ export interface BrowserCapabilityRequest {
3
+ url: string;
4
+ method?: string;
5
+ credentials?: 'omit' | 'same-origin' | 'include';
6
+ redirect?: 'manual' | 'follow';
7
+ cache?: 'default' | 'no-store';
8
+ headers?: Record<string, string>;
9
+ injectedHeaders?: Record<string, string>;
10
+ cookieHeaders?: Record<string, string>;
11
+ withCookies?: boolean;
12
+ /** Reuse the host source-header policy, including XSRF when cookies are requested. */
13
+ withSourceHeaders?: boolean;
14
+ withXsrf?: boolean;
15
+ body?: string;
16
+ formBody?: Record<string, string>;
17
+ }
18
+ export interface BrowserCapabilityResponse {
19
+ ok: boolean;
20
+ status: number;
21
+ statusText: string;
22
+ body: string;
23
+ redirected?: boolean;
24
+ headers?: Record<string, string>;
25
+ }
26
+ export interface BrowserCapabilityHost {
27
+ request(input: BrowserCapabilityRequest): Promise<BrowserCapabilityResponse>;
28
+ cookie(input: {
29
+ url: string;
30
+ name: string;
31
+ withRelatedCookies?: boolean;
32
+ domain?: boolean;
33
+ partitionKey?: {
34
+ topLevelSite: string;
35
+ };
36
+ }): Promise<string | undefined>;
37
+ }
38
+ export interface BrowserCapabilityInvocation {
39
+ code: Uint8Array;
40
+ sha256: string;
41
+ handlers: string[];
42
+ handler?: string;
43
+ input?: unknown;
44
+ config?: JsonObject;
45
+ }
46
+ export declare function buildBrowserCapabilityPage(input: BrowserCapabilityInvocation): Promise<string>;
47
+ export declare function buildBrowserPureCapabilityPage(input: Omit<BrowserCapabilityInvocation, 'handler' | 'input'>): Promise<string>;
@@ -0,0 +1,141 @@
1
+ import { BundleError, MAX_BUNDLE_BYTES, bundleDigest } from './bundle.js';
2
+ import { clonePresetDefaults } from './manifest.js';
3
+ /** This function is serialized into an opaque sandbox, never evaluated by the extension worker. */
4
+ function runBrowserCapability(payload) {
5
+ let connected = false;
6
+ window.addEventListener('message', async (event) => {
7
+ if (event.source !== window.parent || event.data?.type !== 'mearl-plugin-connect' || !event.ports[0] || connected)
8
+ return;
9
+ connected = true;
10
+ const port = event.ports[0];
11
+ const pending = new Map();
12
+ let serial = 0;
13
+ const call = (method, input) => new Promise((resolve, reject) => {
14
+ const id = ++serial;
15
+ pending.set(id, { resolve, reject });
16
+ try {
17
+ port.postMessage({ type: 'host-call', id, method, input });
18
+ }
19
+ catch (error) {
20
+ pending.delete(id);
21
+ reject(error);
22
+ }
23
+ });
24
+ port.onmessage = response => {
25
+ const value = response.data;
26
+ if (value?.type !== 'host-result' || !Number.isSafeInteger(value.id))
27
+ return;
28
+ const request = pending.get(value.id);
29
+ if (!request)
30
+ return;
31
+ pending.delete(value.id);
32
+ if (value.success === true)
33
+ request.resolve(value.value);
34
+ else
35
+ request.reject(new Error(typeof value.error === 'string' ? value.error : 'Browser host call failed'));
36
+ };
37
+ port.start();
38
+ try {
39
+ const module = { exports: {} };
40
+ const evaluate = new Function('module', 'exports', '"use strict";\n' + payload.code);
41
+ evaluate(module, module.exports);
42
+ const factory = module.exports;
43
+ if (typeof factory !== 'function')
44
+ throw new Error('Browser capability must export a factory');
45
+ const handlers = await factory(Object.freeze({ request: (input) => call('request', input), cookie: (input) => call('cookie', input) }), payload.config);
46
+ if (!handlers || typeof handlers !== 'object' || payload.handlers.some(name => !Object.hasOwn(handlers, name) || typeof handlers[name] !== 'function'))
47
+ throw new Error('Browser capability factory is missing a declared handler');
48
+ const value = payload.handler === undefined ? { handlers: payload.handlers } : await handlers[payload.handler](payload.input);
49
+ port.postMessage({ type: 'result', success: true, value });
50
+ }
51
+ catch (error) {
52
+ port.postMessage({ type: 'result', success: false, error: error instanceof Error ? error.message : String(error) });
53
+ }
54
+ });
55
+ window.parent.postMessage({ type: 'mearl-plugin-ready' }, '*');
56
+ }
57
+ /** Both sandbox renderers use the same validated JSON payload. */
58
+ async function encodeBrowserCapability(input) {
59
+ if (!(input.code instanceof Uint8Array) || input.code.byteLength === 0 || input.code.byteLength > MAX_BUNDLE_BYTES)
60
+ throw new BundleError('BUNDLE_QUOTA', 'Invalid browser module size');
61
+ if (!Array.isArray(input.handlers) || input.handlers.length > 256)
62
+ throw new BundleError('BUNDLE_QUOTA', 'Browser module declares too many handlers');
63
+ const handlers = [...input.handlers];
64
+ if (new Set(handlers).size !== handlers.length || handlers.some(name => typeof name !== 'string' || !/^[a-z][a-zA-Z0-9_.-]{0,127}$/.test(name)) || input.handler !== undefined && !handlers.includes(input.handler))
65
+ throw new BundleError('BUNDLE_INVALID', 'Invalid browser module handler');
66
+ const bytes = Uint8Array.from(input.code);
67
+ const config = clonePresetDefaults(input.config ?? {});
68
+ if (new TextEncoder().encode(JSON.stringify(config)).byteLength > 262144)
69
+ throw new BundleError('BUNDLE_QUOTA', 'Browser module configuration exceeds 256 KiB');
70
+ const handler = input.handler;
71
+ let acceptedInput;
72
+ try {
73
+ acceptedInput = input.input === undefined ? undefined : JSON.parse(JSON.stringify(input.input));
74
+ }
75
+ catch {
76
+ throw new BundleError('BUNDLE_INVALID', 'Browser module input must be JSON');
77
+ }
78
+ const sha256 = input.sha256;
79
+ if (!/^[a-f0-9]{64}$/.test(sha256) || await bundleDigest(bytes) !== sha256)
80
+ throw new BundleError('BUNDLE_INTEGRITY', 'Browser module digest does not match');
81
+ let code;
82
+ try {
83
+ code = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
84
+ }
85
+ catch {
86
+ throw new BundleError('BUNDLE_INVALID', 'Browser module must be UTF-8');
87
+ }
88
+ const data = JSON.stringify({ code, handlers, handler, input: acceptedInput, config }).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
89
+ if (new TextEncoder().encode(data).byteLength > 64 * 1024 * 1024)
90
+ throw new BundleError('BUNDLE_QUOTA', 'Browser module invocation exceeds 64 MiB');
91
+ return data;
92
+ }
93
+ export async function buildBrowserCapabilityPage(input) {
94
+ const data = await encodeBrowserCapability(input);
95
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'none'; base-uri 'none'; form-action 'none'"><script>(${runBrowserCapability.toString()})(${data});</script>`;
96
+ }
97
+ /** Serialized into the opaque sandbox; this execution path has no host capabilities. */
98
+ function runPureCapability(payload) {
99
+ let connected = false;
100
+ window.addEventListener('message', async (event) => {
101
+ if (connected || event.source !== window.parent || event.data?.type !== 'mearl-plugin-connect' || !event.ports[0])
102
+ return;
103
+ connected = true;
104
+ const port = event.ports[0];
105
+ try {
106
+ const module = { exports: {} };
107
+ new Function('module', 'exports', '"use strict";\n' + payload.code)(module, module.exports);
108
+ if (typeof module.exports !== 'function')
109
+ throw new Error('Browser capability must export a factory');
110
+ const unavailable = async () => { throw new Error('Host operations are unavailable in a pure runtime'); };
111
+ const handlers = await module.exports(Object.freeze({ request: unavailable, cookie: unavailable }), payload.config);
112
+ if (!handlers || typeof handlers !== 'object' || payload.handlers.some(name => !Object.hasOwn(handlers, name) || typeof handlers[name] !== 'function'))
113
+ throw new Error('Browser capability factory is missing a declared handler');
114
+ port.onmessage = async (event) => {
115
+ const message = event.data;
116
+ if (message?.type !== 'invoke' || !Number.isSafeInteger(message.id))
117
+ return;
118
+ try {
119
+ if (!payload.handlers.includes(message.handler))
120
+ throw new Error('Unknown pure runtime handler');
121
+ const value = await handlers[message.handler](message.input);
122
+ port.postMessage({ type: 'result', id: message.id, success: true, value });
123
+ }
124
+ catch (error) {
125
+ port.postMessage({ type: 'result', id: message.id, success: false, error: error instanceof Error ? error.message : String(error) });
126
+ }
127
+ };
128
+ port.start();
129
+ port.postMessage({ type: 'ready', success: true });
130
+ }
131
+ catch (error) {
132
+ port.postMessage({ type: 'ready', success: false, error: error instanceof Error ? error.message : String(error) });
133
+ }
134
+ });
135
+ window.parent.postMessage({ type: 'mearl-plugin-ready' }, '*');
136
+ }
137
+ export async function buildBrowserPureCapabilityPage(input) {
138
+ const { code, sha256, handlers, config } = input;
139
+ const data = await encodeBrowserCapability({ code, sha256, handlers, config });
140
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'none'; base-uri 'none'; form-action 'none'"><script>(${runPureCapability.toString()})(${data});</script>`;
141
+ }
@@ -0,0 +1,42 @@
1
+ import { type PreparedBundle } from './bundle.js';
2
+ import { type BrowserPresetSnapshot, type PreparedBrowserPreset } from './browserPreset.js';
3
+ import type { BrowserPresetInstallation } from './bundleStore.js';
4
+ import type { JsonObject } from './types.js';
5
+ /** Every encoded response stays well below Native Messaging's one MiB host limit. */
6
+ export declare const PRESET_TRANSFER_CHUNK_BYTES: number;
7
+ export declare const MAX_PRESET_TRANSFER_HEADER_BYTES: number;
8
+ export interface BrowserPresetTransferHeader {
9
+ schemaVersion: 1;
10
+ installationRevision: string;
11
+ snapshot: BrowserPresetSnapshot;
12
+ bundles: Array<Omit<PreparedBundle, 'resources'>>;
13
+ overrides: JsonObject;
14
+ }
15
+ export type PresetTransferRequest = {
16
+ operation: 'open';
17
+ installationRevision: string;
18
+ } | {
19
+ operation: 'read';
20
+ session: string;
21
+ sha256: string;
22
+ offset: number;
23
+ } | {
24
+ operation: 'confirm' | 'release';
25
+ session: string;
26
+ };
27
+ export type PresetTransferTransport = (request: PresetTransferRequest) => Promise<unknown>;
28
+ export declare function readPresetTransferResource(sha256: string, byteLength: number, options: {
29
+ read: (offset: number) => Promise<unknown>;
30
+ signal?: AbortSignal;
31
+ }): Promise<Uint8Array>;
32
+ /** Receives the captured browser projection, excluding Node-only packages and executing no factories. */
33
+ export declare function receiveBrowserPreset(installationRevision: string, options: {
34
+ transport: PresetTransferTransport;
35
+ mearlApiVersion: string;
36
+ signal?: AbortSignal;
37
+ }): Promise<{
38
+ prepared: PreparedBrowserPreset;
39
+ installation: BrowserPresetInstallation;
40
+ confirm: () => Promise<void>;
41
+ release: () => Promise<void>;
42
+ }>;