@jini-ai/plugins 0.7.3-next.2 → 0.7.4
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/CHANGELOG.md +7 -0
- package/README.md +53 -0
- package/dist/host/activation-polling.d.ts +67 -0
- package/dist/host/activation-polling.js +113 -0
- package/dist/host/activation.d.ts +2 -30
- package/dist/host/contributions.d.ts +2 -9
- package/dist/host/contributions.js +1 -1
- package/dist/host/hook-refusals.d.ts +49 -0
- package/dist/host/hook-refusals.js +65 -0
- package/dist/host/index.d.ts +3 -1
- package/dist/host/index.js +1 -0
- package/dist/host/node/browser-provider-assets.d.ts +2 -1
- package/dist/host/node/browser-provider-assets.js +2 -2
- package/dist/host/node/discovery.js +4 -4
- package/dist/host/node/install.d.ts +6 -1
- package/dist/host/node/install.js +20 -18
- package/dist/host/node/integrity-command.d.ts +2 -1
- package/dist/host/node/integrity-command.js +3 -3
- package/dist/host/node/loader.d.ts +3 -2
- package/dist/host/node/loader.js +6 -6
- package/dist/host/node/module-snapshot.d.ts +4 -3
- package/dist/host/node/module-snapshot.js +5 -5
- package/dist/host/node/package-files.d.ts +2 -1
- package/dist/host/node/package-files.js +6 -6
- package/dist/host/node/runtime-activation.d.ts +35 -0
- package/dist/host/node/runtime-activation.js +188 -0
- package/dist/host/node/runtime-boot.d.ts +16 -0
- package/dist/host/node/runtime-boot.js +153 -0
- package/dist/host/node/runtime-conflicts.d.ts +38 -0
- package/dist/host/node/runtime-conflicts.js +42 -0
- package/dist/host/node/runtime-contracts.d.ts +4 -3
- package/dist/host/node/runtime-core.js +65 -465
- package/dist/host/node/runtime-load-target.d.ts +14 -0
- package/dist/host/node/runtime-load-target.js +15 -0
- package/dist/host/node/runtime-reload.d.ts +12 -0
- package/dist/host/node/runtime-reload.js +107 -0
- package/dist/host/node/runtime-state.d.ts +52 -0
- package/dist/host/node/runtime-state.js +50 -0
- package/dist/host/node/source-drafts.d.ts +1 -1
- package/dist/host/node/source-drafts.js +17 -15
- package/dist/host/plugin-claims.d.ts +2 -9
- package/dist/host/plugin-format.d.ts +5 -5
- package/dist/host/plugin-format.js +9 -10
- package/dist/host/ports.d.ts +3 -28
- package/dist/host/tools/install.js +1 -1
- package/dist/host/uninstall.d.ts +2 -2
- package/dist/host/worker/import-policy.d.ts +49 -0
- package/dist/host/worker/import-policy.js +86 -0
- package/dist/host/worker/import-seam.js +21 -2
- package/dist/host/worker/index.d.ts +1 -0
- package/dist/host/worker/index.js +1 -0
- package/dist/host/worker/protocol.d.ts +4 -0
- package/dist/host/worker/run-call.js +2 -1
- package/dist/host/worker/start.d.ts +18 -1
- package/dist/host/worker/start.js +27 -6
- package/dist/react/PluginProviderSettingsDialog.d.ts +144 -0
- package/dist/react/PluginProviderSettingsDialog.js +54 -0
- package/dist/react/plugin-install-port.d.ts +29 -0
- package/dist/react/plugin-install-port.js +15 -0
- package/dist/runtime/agent-tools.d.ts +174 -0
- package/dist/runtime/agent-tools.js +121 -0
- package/dist/runtime/built-ins/word-count/count-words.d.ts +21 -0
- package/dist/runtime/built-ins/word-count/count-words.js +48 -0
- package/dist/runtime/built-ins/word-count/plugin.d.ts +6 -0
- package/dist/runtime/built-ins/word-count/plugin.js +12 -0
- package/dist/runtime/capability-card.d.ts +22 -0
- package/dist/runtime/capability-card.js +30 -0
- package/dist/runtime/enable-confirmation-ui.d.ts +28 -0
- package/dist/runtime/enable-confirmation-ui.js +54 -0
- package/dist/runtime/install-consent.d.ts +12 -0
- package/dist/runtime/install-consent.js +27 -0
- package/dist/runtime/install-source.d.ts +26 -0
- package/dist/runtime/install-source.js +61 -0
- package/dist/runtime/install-tool-catalog.d.ts +9 -0
- package/dist/runtime/install-tool-catalog.js +25 -0
- package/dist/runtime/lower-tool-access.d.ts +17 -0
- package/dist/runtime/lower-tool-access.js +14 -0
- package/dist/runtime/plugin-export.d.ts +13 -0
- package/dist/runtime/plugin-export.js +14 -0
- package/dist/runtime/plugin-host-copy.d.ts +17 -0
- package/dist/runtime/plugin-host-copy.js +7 -0
- package/dist/runtime/plugin-tool-ids.d.ts +18 -0
- package/dist/runtime/plugin-tool-ids.js +4 -0
- package/dist/runtime/plugin-tool-messages.d.ts +97 -0
- package/dist/runtime/plugin-tool-messages.js +90 -0
- package/dist/runtime/sdk-resolver.d.ts +60 -0
- package/dist/runtime/sdk-resolver.js +97 -0
- package/dist/runtime/service-ports.d.ts +43 -0
- package/dist/runtime/service-ports.js +3 -0
- package/dist/runtime/source-tool-catalog.d.ts +7 -0
- package/dist/runtime/source-tool-catalog.js +33 -0
- package/dist/runtime/uninstall-confirmation-ui.d.ts +31 -0
- package/dist/runtime/uninstall-confirmation-ui.js +38 -0
- package/dist/runtime/widget-partials.d.ts +22 -0
- package/dist/runtime/widget-partials.js +13 -0
- package/dist/site/lipay/manifest.d.ts +10 -0
- package/dist/site/lipay/manifest.js +96 -0
- package/dist/site/store/manifest.d.ts +10 -0
- package/dist/site/store/manifest.js +37 -0
- package/package.json +158 -8
- package/dist/host/provider-config-source.d.ts +0 -47
- package/dist/host/provider-config-source.js +0 -2
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Install, source and reload phases of the plugin runtime core (G08 split): the installer port,
|
|
3
|
+
* the source service and the approval-gated reload with its restore rollback.
|
|
4
|
+
* @agent-note Reload: a source reload that widens capabilities throws the host's
|
|
5
|
+
* `text.reloadApprovalRequired` and keeps the approved version running; a failed reload re-enters the
|
|
6
|
+
* same loader for the restored row, and if that fails too the plugin is quarantined with
|
|
7
|
+
* `text.restoreFailedReason`.
|
|
8
|
+
*/
|
|
9
|
+
import { describeErrorForLog } from "@jini-ai/core";
|
|
10
|
+
import { setPluginEnabled } from "../activation.js";
|
|
11
|
+
import { quarantinePlugin } from "../quarantine.js";
|
|
12
|
+
import { addedPluginCapabilities, pluginCapabilitySet } from "../source-policy.js";
|
|
13
|
+
import { installSitePlugin, previewSitePluginInstall, pruneSitePluginVersions } from "./install.js";
|
|
14
|
+
import { createPluginSourceService } from "./source-drafts.js";
|
|
15
|
+
import { onPluginDisabled, onPluginEnabled } from "./runtime-activation.js";
|
|
16
|
+
import { discoverPlugins, installPreviewConflicts } from "./runtime-conflicts.js";
|
|
17
|
+
/** The install deps shared by preview and install. */
|
|
18
|
+
function installDeps({ state, installDir, options }, _options = {}) {
|
|
19
|
+
const { sources, activationRepo } = state.required;
|
|
20
|
+
return { ...state.runtimeBinding, ...options, installDir, builtInIds: sources.map((source) => source.manifest.id), builtInManifests: sources.map((source) => source.manifest), repo: activationRepo, conflicts: ({ manifest }) => installPreviewConflicts({ state, manifest }) };
|
|
21
|
+
}
|
|
22
|
+
export function createPluginInstaller({ state }, _options = {}) {
|
|
23
|
+
const { installDir } = state;
|
|
24
|
+
if (installDir === undefined)
|
|
25
|
+
return undefined;
|
|
26
|
+
return {
|
|
27
|
+
preview: (input, options = {}) => previewSitePluginInstall({ ...input, deps: installDeps({ state, installDir, options }) }),
|
|
28
|
+
install: async (input, options = {}) => {
|
|
29
|
+
const deps = installDeps({ state, installDir, options });
|
|
30
|
+
const preview = await previewSitePluginInstall({ ...input, deps });
|
|
31
|
+
// Admission uses this manifest's identity; publication must retain those exact bytes.
|
|
32
|
+
const run = () => installSitePlugin({ ...input, expectedDigest: input.expectedDigest ?? preview.digest, deps });
|
|
33
|
+
const host = state.optional.lookup?.();
|
|
34
|
+
if (!host)
|
|
35
|
+
return run();
|
|
36
|
+
return host.withInstallIdentity({ candidate: { id: preview.publisherId ?? `unknown/${preview.id}`, localId: preview.id, family: "site-runtime" }, run });
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Callbacks for one row: only this workspace's rows touch live runtime state; other workspaces just re-seal. */
|
|
41
|
+
function activationCallbacks({ state, here }, _options = {}) {
|
|
42
|
+
if (!here)
|
|
43
|
+
return { onEnabled: async () => { } };
|
|
44
|
+
return { onEnabled: (pluginId) => onPluginEnabled({ state, pluginId }) };
|
|
45
|
+
}
|
|
46
|
+
async function reloadActivation({ state, row, id, discovery }, _options = {}) {
|
|
47
|
+
const here = row.workspaceId === state.required.workspaceId;
|
|
48
|
+
try {
|
|
49
|
+
await setPluginEnabled({ deps: { clock: state.required.clock, repo: state.required.activationRepo, discovery,
|
|
50
|
+
...activationCallbacks({ state, here }) },
|
|
51
|
+
input: { workspaceId: row.workspaceId, pluginId: id, enabled: true } });
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (here)
|
|
55
|
+
await restoreReloadedPlugin({ state, id, workspaceId: row.workspaceId });
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function assertReloadApproved({ id, enabledCount, discovery, state, readApproval }, _options = {}) {
|
|
60
|
+
// Consent gap (2026-10-12): a re-seal that widens what a running plugin can reach waits for
|
|
61
|
+
// the owner. Thrown here, the source service reports it as reloadError and keeps every
|
|
62
|
+
// retained version; the approved version keeps running until the owner re-approves it.
|
|
63
|
+
const next = discovery.find(record => record.id === id)?.manifest;
|
|
64
|
+
const added = enabledCount > 0 && next ? addedPluginCapabilities({ approved: await readApproval({ id }), next: pluginCapabilitySet({ manifest: next }) }) : [];
|
|
65
|
+
if (added.length > 0)
|
|
66
|
+
throw new Error(state.required.text.reloadApprovalRequired({ added }));
|
|
67
|
+
}
|
|
68
|
+
async function restoreReloadedPlugin({ state, id, workspaceId }, _options = {}) {
|
|
69
|
+
// setPluginEnabled already restored the old activation row. Re-enter the same loader
|
|
70
|
+
// to pin its retained bytes, rather than turning a working plugin off for a bad update.
|
|
71
|
+
try {
|
|
72
|
+
await onPluginEnabled({ state, pluginId: id });
|
|
73
|
+
}
|
|
74
|
+
catch (rollbackError) {
|
|
75
|
+
console.warn(`[plugin-runtime] Plugin '${id}' restored-version reload failed`, describeErrorForLog({ err: rollbackError }));
|
|
76
|
+
onPluginDisabled({ state, pluginId: id });
|
|
77
|
+
await quarantinePlugin({ deps: state.quarantineDeps, input: { pluginId: id, workspaceId, consecutiveFailures: 0, reason: state.required.text.restoreFailedReason } });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** The reload callback: approval gate, then every enabled row (this workspace first) re-enters the loader. */
|
|
81
|
+
async function reloadPlugin({ state, id, readApproval }, _options = {}) {
|
|
82
|
+
const enabled = (await state.required.activationRepo.listAll()).filter(row => row.pluginId === id && row.enabled);
|
|
83
|
+
const discovery = await discoverPlugins({ state });
|
|
84
|
+
await assertReloadApproved({ state, id, enabledCount: enabled.length, discovery, readApproval });
|
|
85
|
+
// Load here before publishing active pointers to other processes. Their existing poll sees
|
|
86
|
+
// a version change and re-enters the same validated loader, replacing module snapshots.
|
|
87
|
+
enabled.sort((a, b) => Number(b.workspaceId === state.required.workspaceId) - Number(a.workspaceId === state.required.workspaceId));
|
|
88
|
+
for (const row of enabled) {
|
|
89
|
+
await reloadActivation({ state, row, id, discovery });
|
|
90
|
+
}
|
|
91
|
+
return enabled.some(row => row.workspaceId === state.required.workspaceId);
|
|
92
|
+
}
|
|
93
|
+
export function composeSourceService({ state, pluginInstaller }, _options = {}) {
|
|
94
|
+
const { installDir } = state;
|
|
95
|
+
if (installDir === undefined || pluginInstaller === undefined)
|
|
96
|
+
return undefined;
|
|
97
|
+
const { activationRepo, sources } = state.required;
|
|
98
|
+
const service = createPluginSourceService({
|
|
99
|
+
...state.runtimeBinding, installDir, installer: pluginInstaller, policy: state.required.pluginSourcePolicy,
|
|
100
|
+
pruneVersions: ({ id }) => pruneSitePluginVersions({ id, installDir, repo: activationRepo }),
|
|
101
|
+
builtInIds: sources.map(source => source.manifest.id),
|
|
102
|
+
scaffoldEntry: state.required.text.scaffoldEntry,
|
|
103
|
+
reload: ({ id }) => reloadPlugin({ state, id, readApproval: (input) => service.readApproval(input, {}) }),
|
|
104
|
+
});
|
|
105
|
+
return service;
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=runtime-reload.js.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createPluginContributionRegistry } from "../contributions.js";
|
|
2
|
+
import type { AdmittedBrowserProvider } from "../browser-providers.js";
|
|
3
|
+
import { createHookRegistry } from "../hook-registry.js";
|
|
4
|
+
import { createPluginModuleSnapshotLifecycle } from "./module-snapshot.js";
|
|
5
|
+
import type { PluginRuntimeCoreRequired, PluginRuntimeCoreOptional } from "./runtime-contracts.js";
|
|
6
|
+
export interface RuntimeState<TEvent, TOptions> {
|
|
7
|
+
readonly required: PluginRuntimeCoreRequired<TEvent, TOptions>;
|
|
8
|
+
readonly optional: PluginRuntimeCoreOptional<TEvent, TOptions>;
|
|
9
|
+
readonly runtimeBinding: PluginRuntimeCoreRequired<TEvent, TOptions>["hostBinding"] & {
|
|
10
|
+
pluginSdkBinding: PluginRuntimeCoreRequired<TEvent, TOptions>["pluginSdkBinding"];
|
|
11
|
+
};
|
|
12
|
+
readonly installDir: string | undefined;
|
|
13
|
+
readonly quarantineDeps: QuarantineDeps;
|
|
14
|
+
readonly snapshots: ReturnType<typeof createPluginModuleSnapshotLifecycle> | undefined;
|
|
15
|
+
readonly pendingAttachments: Set<Promise<void>>;
|
|
16
|
+
closing: boolean;
|
|
17
|
+
readonly loadedVersions: Map<string, string>;
|
|
18
|
+
readonly browserProviders: Map<string, readonly AdmittedBrowserProvider[]>;
|
|
19
|
+
browserGeneration: number;
|
|
20
|
+
readonly pluginContributions: ReturnType<typeof createPluginContributionRegistry>;
|
|
21
|
+
readonly providerContributions: ReturnType<typeof createPluginContributionRegistry>;
|
|
22
|
+
readonly selectedProviders: Set<string>;
|
|
23
|
+
readonly loadEpochs: Map<string, number>;
|
|
24
|
+
readonly hookRegistry: ReturnType<typeof createHookRegistry>;
|
|
25
|
+
readonly coreClaims: NonNullable<PluginRuntimeCoreOptional["coreClaims"]>;
|
|
26
|
+
}
|
|
27
|
+
type QuarantineDeps = ReturnType<typeof createQuarantineDeps>;
|
|
28
|
+
declare function createQuarantineDeps<TEvent, TOptions>({ required, optional }: {
|
|
29
|
+
required: PluginRuntimeCoreRequired<TEvent, TOptions>;
|
|
30
|
+
optional: PluginRuntimeCoreOptional<TEvent, TOptions>;
|
|
31
|
+
}, _options?: {}): {
|
|
32
|
+
clock: import("@jini-ai/core/primitives").Clock;
|
|
33
|
+
repo: import("@jini-ai/core/contracts/site/plugins-host").PluginActivationRepoPort;
|
|
34
|
+
onQuarantined: ({ pluginId }: {
|
|
35
|
+
pluginId: string;
|
|
36
|
+
workspaceId: string;
|
|
37
|
+
}) => unknown;
|
|
38
|
+
};
|
|
39
|
+
/** `onHookQuarantine` is the activation phase's hook-failure handler; it closes over the state this
|
|
40
|
+
* function returns, so the registry and the state can reference each other without a half-built factory. */
|
|
41
|
+
export declare function createRuntimeState<TEvent, TOptions>({ required, optional, onHookQuarantine }: {
|
|
42
|
+
required: PluginRuntimeCoreRequired<TEvent, TOptions>;
|
|
43
|
+
optional: PluginRuntimeCoreOptional<TEvent, TOptions>;
|
|
44
|
+
onHookQuarantine: (input: {
|
|
45
|
+
pluginId: string;
|
|
46
|
+
workspaceId: string;
|
|
47
|
+
consecutiveFailures: number;
|
|
48
|
+
reason: string;
|
|
49
|
+
}) => Promise<void>;
|
|
50
|
+
}, _options?: {}): RuntimeState<TEvent, TOptions>;
|
|
51
|
+
export {};
|
|
52
|
+
//# sourceMappingURL=runtime-state.d.ts.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The ONE typed state object every phase helper of the plugin runtime core shares (G08 split of
|
|
3
|
+
* `createPluginRuntimeCore`). Built once per runtime; helpers take it as an argument instead of
|
|
4
|
+
* capturing a half-built factory closure.
|
|
5
|
+
* @agent-note Shared state: ONE hook registry (save AND preview), ONE contribution and provider
|
|
6
|
+
* registry and ONE pending-attachment set per runtime. `closing` and `browserGeneration` are the only
|
|
7
|
+
* scalars that change after construction.
|
|
8
|
+
*/
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { createPluginContributionRegistry } from "../contributions.js";
|
|
11
|
+
import { createHookRegistry } from "../hook-registry.js";
|
|
12
|
+
import { createPluginModuleSnapshotLifecycle } from "./module-snapshot.js";
|
|
13
|
+
function createQuarantineDeps({ required, optional }, _options = {}) {
|
|
14
|
+
return { clock: required.clock, repo: required.activationRepo, onQuarantined: ({ pluginId }) => {
|
|
15
|
+
const tracker = optional.tracker?.();
|
|
16
|
+
if (!tracker)
|
|
17
|
+
return undefined;
|
|
18
|
+
const { event, options } = required.quarantineTelemetry({ pluginId });
|
|
19
|
+
return tracker.capture(event, options);
|
|
20
|
+
} };
|
|
21
|
+
}
|
|
22
|
+
/** `onHookQuarantine` is the activation phase's hook-failure handler; it closes over the state this
|
|
23
|
+
* function returns, so the registry and the state can reference each other without a half-built factory. */
|
|
24
|
+
export function createRuntimeState({ required, optional, onHookQuarantine }, _options = {}) {
|
|
25
|
+
const { installDir } = optional;
|
|
26
|
+
return {
|
|
27
|
+
required,
|
|
28
|
+
optional,
|
|
29
|
+
quarantineDeps: createQuarantineDeps({ required, optional }),
|
|
30
|
+
runtimeBinding: { ...required.hostBinding, pluginSdkBinding: required.pluginSdkBinding },
|
|
31
|
+
installDir,
|
|
32
|
+
// The install directory owns versions; its sibling runtime directory owns executable graphs.
|
|
33
|
+
snapshots: installDir === undefined ? undefined : createPluginModuleSnapshotLifecycle({ runtimeRoot: path.resolve(installDir) + "-runtime" }),
|
|
34
|
+
pendingAttachments: new Set(),
|
|
35
|
+
closing: false,
|
|
36
|
+
loadedVersions: new Map(),
|
|
37
|
+
browserProviders: new Map(),
|
|
38
|
+
browserGeneration: 0,
|
|
39
|
+
pluginContributions: createPluginContributionRegistry({}),
|
|
40
|
+
providerContributions: createPluginContributionRegistry({}),
|
|
41
|
+
selectedProviders: new Set(),
|
|
42
|
+
loadEpochs: new Map(),
|
|
43
|
+
hookRegistry: createHookRegistry({ pluginSdkBinding: required.pluginSdkBinding }, {
|
|
44
|
+
...(optional.failureThreshold === undefined ? {} : { failureThreshold: optional.failureThreshold }),
|
|
45
|
+
onQuarantine: onHookQuarantine,
|
|
46
|
+
}),
|
|
47
|
+
coreClaims: optional.coreClaims ?? [],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=runtime-state.js.map
|
|
@@ -79,7 +79,7 @@ export interface PluginSourceDeps extends ManifestHostPorts {
|
|
|
79
79
|
readonly builtInIds: readonly string[];
|
|
80
80
|
readonly installer: PluginInstallerPort;
|
|
81
81
|
readonly policy: PluginSourcePolicyPort;
|
|
82
|
-
/** The host's cross-process file lock (Node hosts pass `
|
|
82
|
+
/** The host's cross-process file lock (Node hosts pass `createFileLockPort({ withFileLock })` of `@jini-ai/node-adapters/fs`). Required: a default would re-import platform. */
|
|
83
83
|
readonly fileLock: FileLockPort;
|
|
84
84
|
/** Host-specific opt-in instructions; omitted hosts receive a neutral refusal. */
|
|
85
85
|
readonly localInstallDisabledMessage?: string;
|
|
@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os';
|
|
|
7
7
|
import * as semver from 'semver';
|
|
8
8
|
import { FileLockTimeoutError } from '@jini-ai/core/contracts/runtime';
|
|
9
9
|
import { validateManifest, validatePluginIdFormat } from '../manifest.js';
|
|
10
|
-
import { PLUGIN_MANIFEST_FILENAME as MANIFEST,
|
|
10
|
+
import { PLUGIN_MANIFEST_FILENAME as MANIFEST, pluginManifestFilenames, canonicalizePluginManifest } from '../plugin-format.js';
|
|
11
11
|
import { computePluginIntegrity, digestSitePluginSnapshot, snapshotSitePluginPackage } from './install.js';
|
|
12
12
|
export { PluginSourceError } from '../plugin-tool-errors.js';
|
|
13
13
|
export const PLUGIN_SOURCE_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 8 * 1024 * 1024, maxEntries: 512 };
|
|
@@ -104,8 +104,8 @@ async function missingSegmentCount(base, segments) {
|
|
|
104
104
|
return missing;
|
|
105
105
|
}
|
|
106
106
|
/** The draft's manifest JSON (current name first, then the legacy alias), or a refusal. */
|
|
107
|
-
function parseDraftManifest(files) {
|
|
108
|
-
const filename =
|
|
107
|
+
function parseDraftManifest(files, manifestFilenames) {
|
|
108
|
+
const filename = manifestFilenames.find(name => files.has(name)); // legacy alias
|
|
109
109
|
try {
|
|
110
110
|
return JSON.parse(filename === undefined ? '' : files.get(filename).toString('utf8'));
|
|
111
111
|
}
|
|
@@ -128,7 +128,7 @@ function createDraftContext(required, optional) {
|
|
|
128
128
|
// Beside the per-version provenance markers, so version pruning never removes it and no draft
|
|
129
129
|
// path (ids cannot start with '.') can write it. Per site: one approval covers every workspace.
|
|
130
130
|
const approval = (id) => path.join(drafts, '.sealed', id, 'approved.json');
|
|
131
|
-
return { required, optional, root, drafts, draft, marker, approval };
|
|
131
|
+
return { required, optional, root, drafts, draft, marker, approval, manifestFilenames: pluginManifestFilenames({}, required) };
|
|
132
132
|
}
|
|
133
133
|
function createDraftLock(ctx) {
|
|
134
134
|
const { required, optional, root } = ctx;
|
|
@@ -184,7 +184,7 @@ function createDraftInstaller(ctx) {
|
|
|
184
184
|
await mkdir(drafts, { recursive: true });
|
|
185
185
|
const staging = await mkdtemp(path.join(drafts, '.open-'));
|
|
186
186
|
try {
|
|
187
|
-
for (const [file, bytes] of canonicalizePluginManifest({ files })) {
|
|
187
|
+
for (const [file, bytes] of canonicalizePluginManifest({ files }, { legacyManifestFilenames: ctx.manifestFilenames })) {
|
|
188
188
|
safeFile(file);
|
|
189
189
|
await writeAtomic(root, path.join(staging, file), bytes);
|
|
190
190
|
} // legacy alias
|
|
@@ -218,7 +218,7 @@ function createDraftWriter(ctx, deps) {
|
|
|
218
218
|
const { snapshot } = deps;
|
|
219
219
|
return async function write(id, file, content) {
|
|
220
220
|
safeFile(file);
|
|
221
|
-
if (file
|
|
221
|
+
if (ctx.manifestFilenames.includes(file))
|
|
222
222
|
file = MANIFEST; // legacy alias
|
|
223
223
|
const { segments, bytes } = draftWriteInput(file, content);
|
|
224
224
|
const files = await snapshot(draft(id));
|
|
@@ -233,7 +233,9 @@ function createDraftWriter(ctx, deps) {
|
|
|
233
233
|
fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 8 MiB or 512 entries.');
|
|
234
234
|
await writeAtomic(root, path.join(draft(id), file), bytes);
|
|
235
235
|
if (file === MANIFEST)
|
|
236
|
-
|
|
236
|
+
for (const alias of ctx.manifestFilenames)
|
|
237
|
+
if (alias !== MANIFEST)
|
|
238
|
+
await rm(path.join(draft(id), alias), { force: true }); // legacy alias
|
|
237
239
|
return { bytesWritten: bytes.length };
|
|
238
240
|
};
|
|
239
241
|
}
|
|
@@ -243,8 +245,8 @@ function createDraftReader(ctx, deps) {
|
|
|
243
245
|
return async function read(id, file) {
|
|
244
246
|
safeFile(file);
|
|
245
247
|
const files = await snapshot(draft(id));
|
|
246
|
-
if (
|
|
247
|
-
file =
|
|
248
|
+
if (ctx.manifestFilenames.includes(file))
|
|
249
|
+
file = ctx.manifestFilenames.find(name => files.has(name)) ?? MANIFEST; // legacy alias
|
|
248
250
|
const bytes = files.get(file);
|
|
249
251
|
if (!bytes)
|
|
250
252
|
fail('PLUGIN_SOURCE_FILE_MISSING', 'The requested file is not in the draft.');
|
|
@@ -267,7 +269,7 @@ function createDraftPublisher(ctx, deps) {
|
|
|
267
269
|
return async function publish(id, files, rollbackFrom) {
|
|
268
270
|
if (!required.policy.localInstallEnabled({}, {}))
|
|
269
271
|
fail('PLUGIN_LOCAL_INSTALL_DISABLED', required.localInstallDisabledMessage ?? 'Local plugin install is disabled by the host.');
|
|
270
|
-
const raw = parseDraftManifest(files);
|
|
272
|
+
const raw = parseDraftManifest(files, ctx.manifestFilenames);
|
|
271
273
|
// `validate` checks the manifest against `folderName: id`, so a manifest whose id is missing or
|
|
272
274
|
// differs from the draft id is already refused there (ID_FOLDER_MISMATCH).
|
|
273
275
|
validate(id, raw);
|
|
@@ -275,7 +277,7 @@ function createDraftPublisher(ctx, deps) {
|
|
|
275
277
|
const version = nextSealVersion((await versions(id))[0], String(manifest.version));
|
|
276
278
|
const staging = await mkdtemp(path.join(optional.temporaryDir ?? tmpdir(), 'plugin-source-'));
|
|
277
279
|
try {
|
|
278
|
-
await stageSealedPackage(staging, files, { ...manifest, version });
|
|
280
|
+
await stageSealedPackage(staging, files, { ...manifest, version }, { legacyManifestFilenames: ctx.manifestFilenames });
|
|
279
281
|
const input = { sourceDir: staging };
|
|
280
282
|
const preview = await required.installer.preview(input, { versionAppend: true });
|
|
281
283
|
const plugin = await required.installer.install({ ...input, expectedDigest: preview.digest }, { versionAppend: true });
|
|
@@ -291,12 +293,12 @@ function createDraftPublisher(ctx, deps) {
|
|
|
291
293
|
};
|
|
292
294
|
}
|
|
293
295
|
/** Writes the draft files, then the manifest with the sealed version and fresh integrity. */
|
|
294
|
-
async function stageSealedPackage(staging, files, manifest) {
|
|
295
|
-
for (const [file, bytes] of canonicalizePluginManifest({ files })) {
|
|
296
|
+
async function stageSealedPackage(staging, files, manifest, optional = {}) {
|
|
297
|
+
for (const [file, bytes] of canonicalizePluginManifest({ files }, optional)) {
|
|
296
298
|
safeFile(file);
|
|
297
299
|
await writeAtomic(staging, path.join(staging, file), bytes);
|
|
298
300
|
} // legacy alias
|
|
299
|
-
const integrity = await computePluginIntegrity({ sourceDir: staging });
|
|
301
|
+
const integrity = await computePluginIntegrity({ sourceDir: staging }, optional);
|
|
300
302
|
await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, integrity }));
|
|
301
303
|
}
|
|
302
304
|
function createDraftReload(ctx) {
|
|
@@ -333,7 +335,7 @@ function draftFileOperations(ctx) {
|
|
|
333
335
|
const manifest = { id, name, version: '0.1.0', engine: 1, sdkRange: '^' + required.pluginSdkBinding.runtimeSdkVersion, tier: 'tier-3', capabilities: [], hooks: [], fields: [], integrity: {} };
|
|
334
336
|
validate(id, manifest);
|
|
335
337
|
await putDraft(id, new Map([[MANIFEST, jsonBytes(manifest)], ['server/index.mjs', Buffer.from(required.scaffoldEntry)], ['README.md', Buffer.from(`${name}\n\n${description}\n\nSite-local tier-3 plugin. Full server access; sandboxing is deferred.\n`)]]));
|
|
336
|
-
const integrity = await computePluginIntegrity({ sourceDir: draft(id) });
|
|
338
|
+
const integrity = await computePluginIntegrity({ sourceDir: draft(id) }, { legacyManifestFilenames: ctx.manifestFilenames });
|
|
337
339
|
await writeAtomic(root, path.join(draft(id), MANIFEST), jsonBytes({ ...manifest, integrity }));
|
|
338
340
|
return { created: true };
|
|
339
341
|
}, { createRoot: true }),
|
|
@@ -4,6 +4,7 @@ import { type ClaimMode, type ExtensionClaim } from "./claim-conflicts.js";
|
|
|
4
4
|
import type { PluginDiscoveryRecord } from "./discovery-types.js";
|
|
5
5
|
import { CORE_OWNER_ID } from "./plugin-format.js";
|
|
6
6
|
import type { PluginManifest } from "./manifest-types.js";
|
|
7
|
+
import type { PluginConflict } from "@jini-ai/core/contracts/site/plugins-host";
|
|
7
8
|
/** The owner id core's claims are filed under, and how messages name it. */
|
|
8
9
|
export { CORE_OWNER_ID };
|
|
9
10
|
/**
|
|
@@ -15,15 +16,7 @@ export { CORE_OWNER_ID };
|
|
|
15
16
|
export declare function capabilityToolIdFor({ pluginId }: {
|
|
16
17
|
pluginId: string;
|
|
17
18
|
}, _optional?: Record<string, never>): string;
|
|
18
|
-
|
|
19
|
-
* holder's display name. */
|
|
20
|
-
export interface PluginConflict {
|
|
21
|
-
readonly kind: string;
|
|
22
|
-
readonly key: string;
|
|
23
|
-
readonly heldBy: string;
|
|
24
|
-
readonly heldByName: string;
|
|
25
|
-
readonly heldKey: string;
|
|
26
|
-
}
|
|
19
|
+
export type { PluginConflict } from "@jini-ai/core/contracts/site/plugins-host";
|
|
27
20
|
/** Every claim one manifest makes (see this file's header for the four sources). */
|
|
28
21
|
export declare function pluginClaimsFromManifest(required: {
|
|
29
22
|
readonly manifest: PluginManifest;
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
/** Plugin wire identifiers. Readers prefer the canonical manifest; publishers emit only it. */
|
|
2
2
|
export declare const PLUGIN_MANIFEST_FILENAME = "jini.plugin.json";
|
|
3
|
-
export declare const LEGACY_PLUGIN_MANIFEST_FILENAME = "tovu.plugin.json";
|
|
4
|
-
export declare const PLUGIN_MANIFEST_FILENAMES: readonly string[];
|
|
5
3
|
export declare const PLUGIN_SDK_SPECIFIER = "@jini-ai/plugin-sdk";
|
|
6
|
-
export
|
|
7
|
-
|
|
4
|
+
export interface PluginManifestReadOptions {
|
|
5
|
+
readonly legacyManifestFilenames?: readonly string[] | undefined;
|
|
6
|
+
}
|
|
7
|
+
export declare function pluginManifestFilenames(_required: Record<string, never>, optional?: PluginManifestReadOptions): readonly string[];
|
|
8
8
|
/** Preserve the selected manifest's exact bytes while dropping alternate manifest filenames.
|
|
9
9
|
* Missing manifests remain missing so the existing validator owns the diagnostic.
|
|
10
10
|
*/
|
|
11
11
|
export declare function canonicalizePluginManifest<T>(required: {
|
|
12
12
|
files: ReadonlyMap<string, T>;
|
|
13
|
-
},
|
|
13
|
+
}, optional?: PluginManifestReadOptions): Map<string, T>;
|
|
14
14
|
/** The owner id the claim system gives the host core (`plugin-claims.ts` re-exports it). Conflict
|
|
15
15
|
* detection never compares an owner with itself, so a plugin with this id would never conflict with
|
|
16
16
|
* core's reserved routes, tools or permissions — it is refused as an id instead. */
|
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
/** Plugin wire identifiers. Readers prefer the canonical manifest; publishers emit only it. */
|
|
2
2
|
export const PLUGIN_MANIFEST_FILENAME = 'jini.plugin.json';
|
|
3
|
-
export const LEGACY_PLUGIN_MANIFEST_FILENAME = 'tovu.plugin.json'; // legacy alias
|
|
4
|
-
export const PLUGIN_MANIFEST_FILENAMES = [PLUGIN_MANIFEST_FILENAME, LEGACY_PLUGIN_MANIFEST_FILENAME]; // legacy alias
|
|
5
3
|
export const PLUGIN_SDK_SPECIFIER = '@jini-ai/plugin-sdk';
|
|
6
|
-
export
|
|
7
|
-
|
|
4
|
+
export function pluginManifestFilenames(_required, optional = {}) {
|
|
5
|
+
return [...new Set([PLUGIN_MANIFEST_FILENAME, ...(optional.legacyManifestFilenames ?? []).filter(name => /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.plugin\.json$/.test(name) && !name.includes('..'))])];
|
|
6
|
+
}
|
|
8
7
|
/** Preserve the selected manifest's exact bytes while dropping alternate manifest filenames.
|
|
9
8
|
* Missing manifests remain missing so the existing validator owns the diagnostic.
|
|
10
9
|
*/
|
|
11
|
-
export function canonicalizePluginManifest(required,
|
|
10
|
+
export function canonicalizePluginManifest(required, optional = {}) {
|
|
12
11
|
const files = new Map(required.files);
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
for (const name of
|
|
16
|
-
files.delete(name);
|
|
12
|
+
const filenames = pluginManifestFilenames({}, optional);
|
|
13
|
+
const selected = filenames.map(name => [...files].find(([key]) => key === name)).find(entry => entry !== undefined);
|
|
14
|
+
for (const name of filenames)
|
|
15
|
+
files.delete(name);
|
|
17
16
|
if (selected !== undefined)
|
|
18
|
-
files.set(PLUGIN_MANIFEST_FILENAME,
|
|
17
|
+
files.set(PLUGIN_MANIFEST_FILENAME, selected[1]);
|
|
19
18
|
return files;
|
|
20
19
|
}
|
|
21
20
|
/** The owner id the claim system gives the host core (`plugin-claims.ts` re-exports it). Conflict
|
package/dist/host/ports.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PluginManifestReadOptions } from "./plugin-format.js";
|
|
1
2
|
/** Host contracts only. No product SDK, content-type implementation or executable importer lives here. */
|
|
2
3
|
import type { PluginManifest, PluginValidationError } from './manifest-types.js';
|
|
3
4
|
import type { PluginDiscoveryRecord } from './discovery-types.js';
|
|
@@ -73,7 +74,7 @@ export interface DeclarativeContentTypesPort {
|
|
|
73
74
|
plan: DeclaredContentTypePlan;
|
|
74
75
|
}, optional?: Record<string, never>): Promise<unknown>;
|
|
75
76
|
}
|
|
76
|
-
export interface ManifestHostPorts<H extends HookPoints = HookPoints> {
|
|
77
|
+
export interface ManifestHostPorts<H extends HookPoints = HookPoints> extends PluginManifestReadOptions {
|
|
77
78
|
/** Host-owned namespace containing publisher id/provides in persisted manifest extensions. */
|
|
78
79
|
readonly identityNamespace: string;
|
|
79
80
|
readonly legacyIdentityNamespace?: string;
|
|
@@ -143,33 +144,7 @@ export interface PluginContributionPorts {
|
|
|
143
144
|
}) => Promise<string>;
|
|
144
145
|
readonly importModule: PluginModuleImportPort;
|
|
145
146
|
}
|
|
146
|
-
|
|
147
|
-
export type RemoveEntity = (required: {
|
|
148
|
-
workspaceId: string;
|
|
149
|
-
id: string;
|
|
150
|
-
display: {
|
|
151
|
-
title: string;
|
|
152
|
-
subtitle?: string | null;
|
|
153
|
-
};
|
|
154
|
-
at: string;
|
|
155
|
-
expectedVersion: number | null;
|
|
156
|
-
actor: {
|
|
157
|
-
principalId: string;
|
|
158
|
-
pluginId?: string | null;
|
|
159
|
-
};
|
|
160
|
-
priorMarker?: string | null;
|
|
161
|
-
}) => Promise<{
|
|
162
|
-
ok: true;
|
|
163
|
-
version: number | null;
|
|
164
|
-
} | {
|
|
165
|
-
ok: false;
|
|
166
|
-
reason: 'not-found' | 'version-changed';
|
|
167
|
-
} | {
|
|
168
|
-
ok: false;
|
|
169
|
-
reason: 'blocked';
|
|
170
|
-
code: string;
|
|
171
|
-
count: number;
|
|
172
|
-
}>;
|
|
147
|
+
export type { RemoveEntity } from "@jini-ai/core/contracts/site/plugins-host";
|
|
173
148
|
/** Review-owned pins supplied by a compiled-in composition source. Never construct these from an
|
|
174
149
|
* installed/custom/marketplace manifest; declaring a tier or provider cannot grant browser trust. */
|
|
175
150
|
export interface BundledBrowserProviderApproval {
|
|
@@ -47,7 +47,7 @@ export function buildPluginInstallRegistrations(deps, _optional = {}) {
|
|
|
47
47
|
const preview = await previewOrRefuse({ installer, input });
|
|
48
48
|
ctx.signal.throwIfAborted();
|
|
49
49
|
try {
|
|
50
|
-
const plugin = await installer.install({ ...input, expectedDigest: preview.digest });
|
|
50
|
+
const plugin = await installer.install({ ...input, expectedDigest: preview.digest }, { signal: ctx.signal });
|
|
51
51
|
deps.telemetry?.installed({ principalId: ctx.principal.id, pluginId: plugin.id });
|
|
52
52
|
return installedResult({ plugin, deps });
|
|
53
53
|
}
|
package/dist/host/uninstall.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { PluginActivationRepoPort } from "./activation.js";
|
|
2
2
|
import type { PluginDiscoveryRecord } from "./discovery-types.js";
|
|
3
|
-
import type {
|
|
3
|
+
import type { RemovePluginFn } from "@jini-ai/core/contracts/site/plugins-host";
|
|
4
4
|
/** A built-in plugin has no on-disk artifact — there is nothing for `DELETE .../plugins/:id` to
|
|
5
5
|
* remove. Distinct from `PluginNotFoundError` (id doesn't exist at all) so the route can map each
|
|
6
6
|
* to its own status code (mirrors `PluginInvalidError`/`PluginIncompatibleError` both being
|
|
@@ -18,7 +18,7 @@ export declare class PluginChangedSincePreviewError extends Error {
|
|
|
18
18
|
}
|
|
19
19
|
export declare class PluginAlreadyInTrashError extends Error {
|
|
20
20
|
}
|
|
21
|
-
export type RemovePluginFn
|
|
21
|
+
export type { RemovePluginFn } from "@jini-ai/core/contracts/site/plugins-host";
|
|
22
22
|
export interface UninstallPluginDeps {
|
|
23
23
|
readonly repo: PluginActivationRepoPort;
|
|
24
24
|
/** Caller-supplied fresh discovery snapshot — same convention as `SetPluginEnabledDeps.discovery`
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** One host trust decision: the exact extra bare specifiers one registered entry's package may import. */
|
|
2
|
+
export interface Tier2TrustedImports {
|
|
3
|
+
/** The registered entry module (path or `file:` URL), matched by real path. */
|
|
4
|
+
readonly entryPath: string;
|
|
5
|
+
/** Exact specifiers; no prefix or directory matching. */
|
|
6
|
+
readonly specifiers: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
/** The host's import policy for every Tier-2 worker it starts. */
|
|
9
|
+
export interface Tier2ImportPolicy {
|
|
10
|
+
/** The SDK specifiers every plugin may import by name (the host's SDK and its aliases). */
|
|
11
|
+
readonly sdkSpecifiers: readonly string[];
|
|
12
|
+
/** Omitted ⇒ SDK-only for every entry. */
|
|
13
|
+
readonly trustedImports?: readonly Tier2TrustedImports[];
|
|
14
|
+
}
|
|
15
|
+
/** What the hook receives through `initialize(data)`. */
|
|
16
|
+
export interface Tier2ImportPolicyData {
|
|
17
|
+
/** `file:` URL of the plugin package, ending in `/`. */
|
|
18
|
+
readonly packageUrl: string;
|
|
19
|
+
readonly allowedSpecifiers: readonly string[];
|
|
20
|
+
readonly sdkSpecifiers: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
export interface Tier2ImportPolicyRequired {
|
|
23
|
+
/** The entry the worker is about to import (path or `file:` URL). */
|
|
24
|
+
readonly entryPath: string;
|
|
25
|
+
/** The plugin's canonical package root from host registration (path or `file:` URL). */
|
|
26
|
+
readonly packageRoot: string;
|
|
27
|
+
readonly policy: Tier2ImportPolicy;
|
|
28
|
+
}
|
|
29
|
+
export interface RegisterTier2ImportPolicyOptional {
|
|
30
|
+
/** Test seam over `node:module`'s `register()`. */
|
|
31
|
+
readonly register?: (specifier: string, options: {
|
|
32
|
+
readonly data: Tier2ImportPolicyData;
|
|
33
|
+
}) => void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Computes the hook's data for one entry. Throws for a malformed `file:` URL or an unreadable path,
|
|
37
|
+
* which the worker start turns into an import-stage reply.
|
|
38
|
+
*
|
|
39
|
+
* @complexity O(t · path length) for t trusted entries.
|
|
40
|
+
*/
|
|
41
|
+
export declare function tier2ImportPolicyData(required: Tier2ImportPolicyRequired, _optional?: Record<string, never>): Tier2ImportPolicyData;
|
|
42
|
+
/**
|
|
43
|
+
* Registers the import policy for this worker's one plugin entry. Call once per worker, before the
|
|
44
|
+
* plugin's first import; the data is computed before anything is registered.
|
|
45
|
+
*
|
|
46
|
+
* @complexity O(t · path length), see {@link tier2ImportPolicyData}.
|
|
47
|
+
*/
|
|
48
|
+
export declare function registerTier2ImportPolicy(required: Tier2ImportPolicyRequired, optional?: RegisterTier2ImportPolicyOptional): void;
|
|
49
|
+
//# sourceMappingURL=import-policy.d.ts.map
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The Tier-2 import policy: a Node module-resolution hook that limits what ONE Tier-2 plugin's
|
|
3
|
+
* own modules may import inside its worker. Node adapter only (`node:module` `register()`).
|
|
4
|
+
*
|
|
5
|
+
* A module inside the plugin's package (the canonical root the host registered — an installed
|
|
6
|
+
* package's root, or a built-in's declared sourceDir — which must contain the entry) may
|
|
7
|
+
* import by name only the host's SDK specifiers plus any EXACT specifiers the host trusts for that
|
|
8
|
+
* entry; `node:fs`, `child_process`, npm packages, `data:` modules and `#imports` are refused. A path
|
|
9
|
+
* import must stay inside the package, or a `../..` climb would reach the same modules. Code outside
|
|
10
|
+
* the package (the SDK build, a trusted host module, the host's own lazy imports) resolves as before.
|
|
11
|
+
*
|
|
12
|
+
* The host supplies the SDK specifiers and its trust decisions; Jini names no product module.
|
|
13
|
+
* The SDK resolver is the host's own hook; this policy only allows its specifiers through, so the
|
|
14
|
+
* two hooks give the same answer whichever is registered first.
|
|
15
|
+
*/
|
|
16
|
+
import { realpathSync } from "node:fs";
|
|
17
|
+
import { register as registerModuleHooks } from "node:module";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
20
|
+
/** The hook module, registered as a `data:` URL so it needs no file kept in sync with `dist/`. */
|
|
21
|
+
const HOOK_MODULE_SOURCE = `
|
|
22
|
+
let packageUrl;
|
|
23
|
+
let allowedSpecifiers;
|
|
24
|
+
let sdkSpecifiers;
|
|
25
|
+
export function initialize(data) { packageUrl = data.packageUrl; allowedSpecifiers = data.allowedSpecifiers; sdkSpecifiers = data.sdkSpecifiers; }
|
|
26
|
+
function refuse(specifier, reason) {
|
|
27
|
+
throw new Error("This plugin may not import " + JSON.stringify(specifier) + ": " + reason);
|
|
28
|
+
}
|
|
29
|
+
export async function resolve(specifier, context, nextResolve) {
|
|
30
|
+
if (!String(context.parentURL).startsWith(packageUrl) || allowedSpecifiers.includes(specifier)) {
|
|
31
|
+
return nextResolve(specifier, context);
|
|
32
|
+
}
|
|
33
|
+
if (!/^(\\.{0,2}\\/|file:)/.test(specifier)) {
|
|
34
|
+
refuse(specifier, "a plugin may import only the plugin SDK (" + sdkSpecifiers.join(", ") + ") and its own files.");
|
|
35
|
+
}
|
|
36
|
+
const resolved = await nextResolve(specifier, context);
|
|
37
|
+
if (!resolved.url.startsWith(packageUrl)) refuse(specifier, "it is outside its own package.");
|
|
38
|
+
return resolved;
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
function realEntryFile(entryPath) {
|
|
42
|
+
const filePath = entryPath.startsWith("file:") ? fileURLToPath(entryPath) : entryPath;
|
|
43
|
+
try {
|
|
44
|
+
// Real paths, because the loader reports a module's real path as its `parentURL`.
|
|
45
|
+
return realpathSync(filePath);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
// A missing entry fails at import with Node's own plain message; anything else is a real fault.
|
|
49
|
+
if (error.code === "ENOENT")
|
|
50
|
+
return filePath;
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Computes the hook's data for one entry. Throws for a malformed `file:` URL or an unreadable path,
|
|
56
|
+
* which the worker start turns into an import-stage reply.
|
|
57
|
+
*
|
|
58
|
+
* @complexity O(t · path length) for t trusted entries.
|
|
59
|
+
*/
|
|
60
|
+
export function tier2ImportPolicyData(required, _optional = {}) {
|
|
61
|
+
const entryFile = realEntryFile(required.entryPath);
|
|
62
|
+
const packageRoot = realEntryFile(required.packageRoot);
|
|
63
|
+
const relative = path.relative(packageRoot, entryFile);
|
|
64
|
+
if (relative === "" || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
65
|
+
throw new Error(`The plugin entry ${JSON.stringify(entryFile)} is not inside its registered package ${JSON.stringify(packageRoot)}.`);
|
|
66
|
+
}
|
|
67
|
+
const { sdkSpecifiers, trustedImports = [] } = required.policy;
|
|
68
|
+
const trusted = trustedImports.filter((decision) => realEntryFile(decision.entryPath) === entryFile).flatMap((decision) => decision.specifiers);
|
|
69
|
+
return {
|
|
70
|
+
packageUrl: pathToFileURL(packageRoot).href.replace(/\/?$/, "/"),
|
|
71
|
+
allowedSpecifiers: [...sdkSpecifiers, ...trusted],
|
|
72
|
+
sdkSpecifiers: [...sdkSpecifiers],
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Registers the import policy for this worker's one plugin entry. Call once per worker, before the
|
|
77
|
+
* plugin's first import; the data is computed before anything is registered.
|
|
78
|
+
*
|
|
79
|
+
* @complexity O(t · path length), see {@link tier2ImportPolicyData}.
|
|
80
|
+
*/
|
|
81
|
+
export function registerTier2ImportPolicy(required, optional = {}) {
|
|
82
|
+
const data = tier2ImportPolicyData(required);
|
|
83
|
+
const register = optional.register ?? ((specifier, options) => registerModuleHooks(specifier, options));
|
|
84
|
+
register(`data:text/javascript,${encodeURIComponent(HOOK_MODULE_SOURCE)}`, { data });
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=import-policy.js.map
|