@mmon-co/ncept-local 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ import { type OAuthClientProvider, type OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js";
2
+ import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
3
+ import type { HubOptions } from "./host.js";
4
+ /** SDK owns discovery, issuer/resource binding, dynamic registration, PKCE and refresh. */
5
+ export declare class HubAuth implements OAuthClientProvider {
6
+ readonly resource: string;
7
+ private readonly path;
8
+ private readonly openUrl;
9
+ readonly clientMetadataUrl?: string | undefined;
10
+ private credentials;
11
+ private verifier?;
12
+ private authorize?;
13
+ private nonce;
14
+ private constructor();
15
+ static open(resource: string, options: HubOptions): Promise<HubAuth>;
16
+ get redirectUrl(): string | undefined;
17
+ get clientMetadata(): {
18
+ client_name: string;
19
+ redirect_uris: string[];
20
+ grant_types: string[];
21
+ response_types: string[];
22
+ token_endpoint_auth_method: string;
23
+ scope: string;
24
+ };
25
+ state(): string;
26
+ clientInformation(): OAuthClientInformationMixed | undefined;
27
+ saveClientInformation(client: OAuthClientInformationMixed): Promise<void>;
28
+ tokens(): {
29
+ access_token: string;
30
+ token_type: string;
31
+ id_token?: string | undefined;
32
+ expires_in?: number | undefined;
33
+ scope?: string | undefined;
34
+ refresh_token?: string | undefined;
35
+ issuer?: string | undefined;
36
+ } | undefined;
37
+ saveTokens(tokens: OAuthTokens): Promise<void>;
38
+ discoveryState(): OAuthDiscoveryState | undefined;
39
+ saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void>;
40
+ saveCodeVerifier(verifier: string): void;
41
+ codeVerifier(): string;
42
+ redirectToAuthorization(url: URL): Promise<void>;
43
+ invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
44
+ private save;
45
+ signIn(): Promise<void>;
46
+ }
@@ -0,0 +1,171 @@
1
+ import { createServer } from "node:http";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { randomBytes, randomUUID } from "node:crypto";
5
+ import { execFile } from "node:child_process";
6
+ import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
7
+ import { credentialsPath } from "./directory.js";
8
+ const scopes = "patches publish learn";
9
+ async function load(path) {
10
+ try {
11
+ const stored = JSON.parse(await readFile(path, "utf8"));
12
+ return stored;
13
+ }
14
+ catch (error) {
15
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
16
+ return {};
17
+ throw error;
18
+ }
19
+ }
20
+ async function browser(url) {
21
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
22
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
23
+ await new Promise((resolve, reject) => {
24
+ execFile(command, args, (error) => error ? reject(new Error("Cannot open the sign-in browser; supply hub.openUrl")) : resolve());
25
+ });
26
+ }
27
+ /** SDK owns discovery, issuer/resource binding, dynamic registration, PKCE and refresh. */
28
+ export class HubAuth {
29
+ resource;
30
+ path;
31
+ openUrl;
32
+ clientMetadataUrl;
33
+ credentials = {};
34
+ verifier;
35
+ authorize;
36
+ nonce = "";
37
+ constructor(resource, path, openUrl, clientMetadataUrl) {
38
+ this.resource = resource;
39
+ this.path = path;
40
+ this.openUrl = openUrl;
41
+ this.clientMetadataUrl = clientMetadataUrl;
42
+ }
43
+ static async open(resource, options) {
44
+ const provider = new HubAuth(resource, options.credentialsFile ?? credentialsPath(), options.openUrl ?? browser, options.clientMetadataUrl);
45
+ provider.credentials = (await load(provider.path))[resource] ?? {};
46
+ return provider;
47
+ }
48
+ get redirectUrl() {
49
+ return this.credentials.redirect;
50
+ }
51
+ get clientMetadata() {
52
+ return {
53
+ client_name: "Common Concept local",
54
+ redirect_uris: this.redirectUrl ? [this.redirectUrl] : [],
55
+ grant_types: ["authorization_code", "refresh_token"],
56
+ response_types: ["code"],
57
+ token_endpoint_auth_method: "none",
58
+ scope: scopes,
59
+ };
60
+ }
61
+ state() {
62
+ return this.nonce;
63
+ }
64
+ clientInformation() {
65
+ return this.credentials.client;
66
+ }
67
+ async saveClientInformation(client) {
68
+ await this.save({ client });
69
+ }
70
+ tokens() {
71
+ return this.credentials.tokens;
72
+ }
73
+ async saveTokens(tokens) {
74
+ // Some issuers rotate refresh tokens; others omit one on refresh.
75
+ await this.save({
76
+ tokens: {
77
+ ...tokens,
78
+ refresh_token: tokens.refresh_token ??
79
+ (tokens.issuer === this.credentials.tokens?.issuer ? this.credentials.tokens?.refresh_token : undefined),
80
+ },
81
+ });
82
+ }
83
+ discoveryState() {
84
+ return this.credentials.discovery;
85
+ }
86
+ async saveDiscoveryState(discovery) {
87
+ await this.save({ discovery });
88
+ }
89
+ saveCodeVerifier(verifier) {
90
+ this.verifier = verifier;
91
+ }
92
+ codeVerifier() {
93
+ if (!this.verifier)
94
+ throw new Error("No sign-in is in progress");
95
+ return this.verifier;
96
+ }
97
+ async redirectToAuthorization(url) {
98
+ if (!this.authorize)
99
+ throw new Error("Sign in first with host.hub.signIn()");
100
+ await this.authorize(url);
101
+ }
102
+ async invalidateCredentials(scope) {
103
+ if (scope === "all" || scope === "verifier")
104
+ this.verifier = undefined;
105
+ if (scope === "all")
106
+ this.credentials = {};
107
+ else if (scope !== "verifier")
108
+ delete this.credentials[scope];
109
+ await this.save({});
110
+ }
111
+ async save(change) {
112
+ this.credentials = { ...this.credentials, ...change };
113
+ const all = { ...(await load(this.path)), [this.resource]: this.credentials };
114
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
115
+ const temporary = this.path + "." + randomUUID() + ".tmp";
116
+ await writeFile(temporary, JSON.stringify(all) + "\n", { mode: 0o600, flag: "wx" });
117
+ await rename(temporary, this.path);
118
+ }
119
+ async signIn() {
120
+ this.nonce = randomBytes(32).toString("base64url");
121
+ let accept;
122
+ let refuse;
123
+ const callback = new Promise((resolve, reject) => {
124
+ accept = resolve;
125
+ refuse = reject;
126
+ });
127
+ // The callback can arrive while discovery/openUrl is still pending.
128
+ void callback.catch(() => { });
129
+ const server = createServer((request, response) => {
130
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
131
+ if (request.method !== "GET" || url.pathname !== "/callback" || url.searchParams.get("state") !== this.nonce) {
132
+ response.writeHead(400).end("Invalid sign-in callback");
133
+ return;
134
+ }
135
+ const code = url.searchParams.get("code");
136
+ const error = url.searchParams.get("error");
137
+ response
138
+ .writeHead(code && !error ? 200 : 400, { "Content-Type": "text/plain", "Cache-Control": "no-store" })
139
+ .end(code && !error ? "Signed in. You can close this window." : "Sign-in was refused.");
140
+ if (code && !error)
141
+ accept(code);
142
+ else
143
+ refuse(new Error("Sign-in refused: " + (error ?? "missing authorization code")));
144
+ });
145
+ const timeout = setTimeout(() => refuse(new Error("Sign-in timed out after five minutes")), 5 * 60_000);
146
+ try {
147
+ await new Promise((resolve, reject) => {
148
+ server.once("error", reject);
149
+ server.listen(0, "127.0.0.1", resolve);
150
+ });
151
+ const address = server.address();
152
+ if (!address || typeof address === "string")
153
+ throw new Error("Cannot start sign-in callback");
154
+ const redirect = "http://127.0.0.1:" + address.port + "/callback";
155
+ // A fresh ephemeral callback must be registered, not silently reuse another redirect URI.
156
+ await this.save({ redirect, client: undefined, tokens: undefined });
157
+ this.authorize = (url) => this.openUrl(url.href);
158
+ const metadata = new URL(this.resource.replace(/\/mcp$/, "/.well-known/oauth-protected-resource"));
159
+ const result = await auth(this, { serverUrl: this.resource, resourceMetadataUrl: metadata, scope: scopes });
160
+ if (result === "REDIRECT")
161
+ await auth(this, { serverUrl: this.resource, authorizationCode: await callback, scope: scopes });
162
+ }
163
+ finally {
164
+ clearTimeout(timeout);
165
+ this.authorize = undefined;
166
+ this.verifier = undefined;
167
+ server.closeAllConnections();
168
+ await new Promise((resolve) => server.close(() => resolve()));
169
+ }
170
+ }
171
+ }
package/dist/hub.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { type ProfileDirectory } from "./directory.js";
2
+ import { type ConfiguredTheory } from "./exchange.js";
3
+ import type { Confirm, Host, HubOptions } from "./host.js";
4
+ export declare function connectHub(profile: ProfileDirectory, theories: readonly ConfiguredTheory[], confirm: Confirm, options?: HubOptions): Host["hub"];
package/dist/hub.js ADDED
@@ -0,0 +1,334 @@
1
+ import { mkdtemp, rename, rm } from "node:fs/promises";
2
+ import { dirname, basename, join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { createRequire } from "node:module";
5
+ import { attachmentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isPatchId, migrateTheoryPatchClosure, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
6
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
+ import { HubAuth } from "./hub-auth.js";
9
+ import { unpackDirectory } from "./directory.js";
10
+ import { object, parsePiSession } from "./sessions.js";
11
+ import { validate, unpack } from "./exchange.js";
12
+ function baseUrl(value) {
13
+ const url = new URL(value);
14
+ if ((url.protocol !== "https:" &&
15
+ !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
16
+ url.username ||
17
+ url.password ||
18
+ url.search ||
19
+ url.hash)
20
+ throw new Error("Hub URL must use HTTPS (or loopback HTTP)");
21
+ return url.href.replace(/\/$/, "");
22
+ }
23
+ function releaseAddress(value, base) {
24
+ const page = value.match(/^(https?:\/\/.+)\/hub\/([^/]+)\/releases\/([^/?#]+)(?:[?#].*)?$/);
25
+ const api = value.match(/^(https?:\/\/.+)\/hub\/v1\/releases\/([^/]+)\/([^/?#]+)(?:[?#].*)?$/);
26
+ const exact = value.match(/^(patch-[0-9a-z-]+)@(.+)$/);
27
+ const match = page ?? api;
28
+ const patchId = match ? decodeURIComponent(match[2] ?? "") : exact?.[1];
29
+ const version = match ? decodeURIComponent(match[3] ?? "") : exact?.[2];
30
+ if (!isPatchId(patchId) || !version)
31
+ throw new Error("Use a Hub release page URL or patch-id@version");
32
+ releasePrecedenceKey(version);
33
+ return { base: match ? baseUrl(match[1] ?? "") : base, patchId, version };
34
+ }
35
+ function releasePath(patchId, version) {
36
+ return "/hub/v1/releases/" + encodeURIComponent(patchId) + "/" + encodeURIComponent(version);
37
+ }
38
+ async function fetched(url, init) {
39
+ const response = await fetch(url, { ...init, signal: AbortSignal.timeout(120_000) });
40
+ if (!response.ok)
41
+ throw new Error("Hub request failed (" + response.status + "): " + (await response.text()));
42
+ return response;
43
+ }
44
+ function attachments(bundle) {
45
+ const found = new Map();
46
+ const add = (values) => {
47
+ for (const value of values)
48
+ if (isAttachment(value))
49
+ found.set(value.hash, value);
50
+ };
51
+ for (const revision of bundle.revisions) {
52
+ add(Object.values(revision.metadata.properties));
53
+ for (const operation of revision.delta.operations) {
54
+ if (operation.kind === "add-metadata-set")
55
+ add(Object.values(operation.metadataSet.properties));
56
+ if (operation.kind === "add-material" || operation.kind === "edit-material") {
57
+ add([operation.material.content, ...Object.values(operation.material.meta)]);
58
+ }
59
+ }
60
+ }
61
+ return [...found.values()];
62
+ }
63
+ /** Reject malformed wire data before handing its typed operations to Core's bundle verifier. */
64
+ function verifiedBundle(value) {
65
+ if (!object(value) || !object(value.terminal) || !Array.isArray(value.revisions))
66
+ throw new Error("Invalid Hub bundle");
67
+ const exact = (ref) => object(ref) && isPatchId(ref.identity) && isContentDigest(ref.digest);
68
+ if (!exact(value.terminal))
69
+ throw new Error("Invalid Hub terminal");
70
+ const isRevision = (revision) => object(revision) &&
71
+ exact(revision.ref) &&
72
+ Array.isArray(revision.bases) &&
73
+ revision.bases.every(exact) &&
74
+ object(revision.delta) &&
75
+ Array.isArray(revision.delta.operations) &&
76
+ object(revision.metadata) &&
77
+ object(revision.metadata.properties) &&
78
+ Array.isArray(revision.metadata.citations);
79
+ const revisions = value.revisions.map((revision) => {
80
+ if (!isRevision(revision))
81
+ throw new Error("Invalid Hub revision");
82
+ return revision;
83
+ });
84
+ const bundle = { terminal: value.terminal, revisions };
85
+ resolvePatchBundle(bundle);
86
+ return bundleForRevision(bundle.terminal, new Map(revisions.map((revision) => [revision.ref.digest, revisionContent(revision)])));
87
+ }
88
+ function theoryRequirement(value) {
89
+ if (!object(value) ||
90
+ typeof value.theory !== "string" ||
91
+ !value.theory.trim() ||
92
+ typeof value.range !== "string" ||
93
+ !/^~(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value.range))
94
+ throw new Error("Invalid Hub release Theory requirement");
95
+ return { theory: value.theory, range: value.range };
96
+ }
97
+ export function connectHub(profile, theories, confirm, options = {}) {
98
+ const base = baseUrl(options.url ?? "https://co.mmon.co/ncept");
99
+ const resource = base + "/mcp";
100
+ const { version } = createRequire(import.meta.url)("../package.json");
101
+ const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + version };
102
+ async function connected(operation) {
103
+ const provider = await HubAuth.open(resource, options);
104
+ if (!provider.tokens())
105
+ throw new Error("Sign in first with host.hub.signIn()");
106
+ const client = new Client({ name: "@mmon-co/ncept-local", version: "0.1.0" });
107
+ try {
108
+ await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
109
+ return await operation(async (name, args) => {
110
+ const result = await client.callTool({ name, arguments: args });
111
+ const text = Array.isArray(result.content)
112
+ ? result.content
113
+ .filter((item) => item.type === "text")
114
+ .map((item) => item.text)
115
+ .join("\n")
116
+ : "";
117
+ if (result.isError)
118
+ throw new Error(text || "Hub tool failed: " + name);
119
+ const parsed = JSON.parse(text);
120
+ return parsed;
121
+ });
122
+ }
123
+ finally {
124
+ await client.close();
125
+ }
126
+ }
127
+ async function upload(call, bytes, mediaType) {
128
+ const hash = attachmentDigest(bytes);
129
+ const capability = await call("upload", { hash, mediaType, byteLength: bytes.length });
130
+ if (bytes.length > capability.maxBytes)
131
+ throw new Error("Upload exceeds the Hub's byte limit");
132
+ await fetched(capability.url, {
133
+ method: capability.method,
134
+ headers: capability.headers,
135
+ body: new Uint8Array(bytes),
136
+ });
137
+ return hash;
138
+ }
139
+ return {
140
+ async pull(address) {
141
+ const selected = releaseAddress(address, base);
142
+ const endpoint = selected.base + releasePath(selected.patchId, selected.version);
143
+ const response = await (await fetched(endpoint, { headers })).json();
144
+ if (!object(response) || response.patchId !== selected.patchId || response.version !== selected.version)
145
+ throw new Error("Hub release address mismatch");
146
+ const requirement = theoryRequirement(response.theoryRequirement);
147
+ const bundle = verifiedBundle(response.bundle);
148
+ if (bundle.terminal.identity !== selected.patchId)
149
+ throw new Error("Hub release identity mismatch");
150
+ const revisions = new Map(bundle.revisions.map((revision) => [exactPatchRefKey(revision.ref), revision]));
151
+ if (!Array.isArray(response.baseTheoryRequirements))
152
+ throw new Error("Invalid Hub base Theory requirements");
153
+ const baseRequirements = new Map();
154
+ for (const declaration of response.baseTheoryRequirements) {
155
+ if (!object(declaration) ||
156
+ !object(declaration.ref) ||
157
+ !isPatchId(declaration.ref.identity) ||
158
+ !isContentDigest(declaration.ref.digest))
159
+ throw new Error("Invalid Hub base Theory requirement");
160
+ const key = exactPatchRefKey({ identity: declaration.ref.identity, digest: declaration.ref.digest });
161
+ if (!revisions.has(key) || baseRequirements.has(key) || key === exactPatchRefKey(bundle.terminal))
162
+ throw new Error("Invalid Hub base Theory requirement");
163
+ baseRequirements.set(key, theoryRequirement(declaration.requirement));
164
+ }
165
+ const blobs = new Map();
166
+ for (const { hash } of attachments(bundle)) {
167
+ const bytes = new Uint8Array(await (await fetched(endpoint + "/attachments/" + hash, { headers })).arrayBuffer());
168
+ if (attachmentDigest(bytes) !== hash)
169
+ throw new Error("Hub attachment digest mismatch: " + hash);
170
+ blobs.set(hash, bytes);
171
+ }
172
+ const current = await profile.read();
173
+ const theory = resolveTheory(current.manifest.theory, theories);
174
+ let migrated;
175
+ let adopted;
176
+ try {
177
+ ({ terminal: adopted, revisions: migrated } = migrateTheoryPatchClosure(theory, bundle, requirement, baseRequirements));
178
+ }
179
+ catch (error) {
180
+ throw new Error("Cannot adopt Hub release; its publisher must republish for the installed Theory: " + String(error));
181
+ }
182
+ const contents = new Map(current.patches.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
183
+ for (const revision of bundle.revisions)
184
+ contents.set(revision.ref.digest, revisionContent(revision));
185
+ for (const revision of migrated)
186
+ contents.set(revision.ref.digest, revisionContent(revision));
187
+ const personal = current.patches.revisions.find(({ ref }) => sameExactPatchRef(ref, current.manifest.personal));
188
+ if (!personal)
189
+ throw new Error("Missing personal Patch");
190
+ const content = {
191
+ ...revisionContent(personal),
192
+ bases: [...personal.bases.filter((ref) => ref.identity !== adopted.ref.identity), adopted.ref],
193
+ };
194
+ const next = candidateRevision(personal.ref.identity, content);
195
+ contents.set(next.ref.digest, content);
196
+ resolvePatchBundle(bundleForRevision(next.ref, contents));
197
+ // Nothing touches the live head until every downloaded revision and blob verifies.
198
+ for (const bytes of blobs.values())
199
+ await profile.addBlob(bytes);
200
+ for (const revision of bundle.revisions)
201
+ await profile.addRevision(revision.ref.identity, revisionContent(revision));
202
+ for (const revision of migrated)
203
+ if (!revisions.has(exactPatchRefKey(revision.ref)))
204
+ await profile.addRevision(revision.ref.identity, revisionContent(revision));
205
+ await profile.setPersonal(await profile.addRevision(personal.ref.identity, content));
206
+ return adopted.ref;
207
+ },
208
+ async signIn() {
209
+ await (await HubAuth.open(resource, options)).signIn();
210
+ },
211
+ async publish(input) {
212
+ releasePrecedenceKey(input.version);
213
+ const current = await profile.read();
214
+ const contents = new Map(current.patches.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
215
+ const original = bundleForRevision(input.patch, contents);
216
+ const terminal = original.revisions.find(({ ref }) => sameExactPatchRef(ref, input.patch));
217
+ if (!terminal)
218
+ throw new Error("Patch is not in this Profile");
219
+ const packaged = {
220
+ ...revisionContent(terminal),
221
+ metadata: {
222
+ ...terminal.metadata,
223
+ properties: {
224
+ ...terminal.metadata.properties,
225
+ "patch:title": input.title,
226
+ ...(input.description === undefined ? {} : { "patch:description": input.description }),
227
+ },
228
+ },
229
+ };
230
+ const ref = candidateRevision(input.patch.identity, packaged).ref;
231
+ contents.set(ref.digest, packaged);
232
+ const bundle = bundleForRevision(ref, contents);
233
+ resolvePatchBundle(bundle);
234
+ if (!(await confirm({
235
+ kind: "hub.publish",
236
+ title: "Publish " + input.title + " " + input.version,
237
+ description: "Publish this Patch and its attachments publicly on the Hub.",
238
+ detail: { ...input, bundle },
239
+ })))
240
+ throw new Error("Publication declined");
241
+ return connected(async (call) => {
242
+ for (const attachment of attachments(bundle)) {
243
+ const bytes = current.blobs.get(attachment.hash);
244
+ if (!bytes)
245
+ throw new Error("Missing Profile blob: " + attachment.hash);
246
+ await upload(call, bytes, attachment.mediaType);
247
+ }
248
+ const captured = await call("capture", { bundle });
249
+ await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version: input.version });
250
+ await call("publish", { patchId: captured.ref.identity, version: input.version });
251
+ return {
252
+ ref: captured.ref,
253
+ version: input.version,
254
+ url: base + "/hub/" + captured.ref.identity + "/releases/" + encodeURIComponent(input.version),
255
+ };
256
+ });
257
+ },
258
+ async exportTo() {
259
+ const archive = await profile.pack();
260
+ await connected(async (call) => {
261
+ const hash = await upload(call, archive, "application/x-tar");
262
+ const preview = await call("import_profile", { hash });
263
+ let missions;
264
+ if (preview.status === "choose-missions") {
265
+ missions = [];
266
+ for (const mission of preview.missions) {
267
+ if (preview.available !== null && missions.length >= preview.available)
268
+ break;
269
+ if (await confirm({
270
+ kind: "hub.choose-mission",
271
+ title: "Keep Mission: " + mission.statement,
272
+ description: "Choose Missions to move to the web within your allowance, or upgrade on the web first.",
273
+ detail: { mission, available: preview.available, upgrade: preview.upgrade },
274
+ }))
275
+ missions.push(mission.id);
276
+ }
277
+ }
278
+ if (!(await confirm({
279
+ kind: "hub.export",
280
+ title: "Replace web Main with this local Profile",
281
+ description: "The old web Main is retained as history. Unchosen Missions remain here locally.",
282
+ detail: { ...preview, chosenMissions: missions },
283
+ })))
284
+ return;
285
+ const result = await call("import_profile", {
286
+ hash,
287
+ expectedMainProfileId: preview.mainProfileId,
288
+ ...(missions === undefined ? {} : { missions }),
289
+ });
290
+ if (result.status !== "imported")
291
+ throw new Error("Web import needs a new preview: " + JSON.stringify(result));
292
+ });
293
+ },
294
+ async importFrom() {
295
+ const archive = await connected(async (call) => {
296
+ const download = await call("export_profile", {});
297
+ return new Uint8Array(await (await fetched(download.url)).arrayBuffer());
298
+ });
299
+ const imported = validate(unpack(archive, theories), theories);
300
+ const backup = profile.dir + ".backup-" + randomUUID();
301
+ if (!(await confirm({
302
+ kind: "hub.import",
303
+ title: "Replace this local Profile with your web Profile",
304
+ description: "Keep the previous directory at " + backup + ". Reopen your Session after importing.",
305
+ detail: { backup, personal: imported.manifest.personal, sessions: [...imported.sessions.keys()] },
306
+ })))
307
+ return { missions: [], sessions: [] };
308
+ const staging = await mkdtemp(join(dirname(profile.dir), "." + basename(profile.dir) + "-import-"));
309
+ try {
310
+ await unpackDirectory(archive, staging, theories);
311
+ await rename(profile.dir, backup);
312
+ try {
313
+ await rename(staging, profile.dir);
314
+ }
315
+ catch (error) {
316
+ await rename(backup, profile.dir);
317
+ throw error;
318
+ }
319
+ }
320
+ finally {
321
+ await rm(staging, { recursive: true, force: true });
322
+ }
323
+ // Relocate transcript headers from the staging directory to their final project.
324
+ const { openProfile } = await import("./directory.js");
325
+ await openProfile(profile.dir, theories);
326
+ return {
327
+ missions: [
328
+ ...new Set(imported.log.flatMap((entry) => "kind" in entry && entry.kind === "mission.revised" ? [entry.mission.id] : [])),
329
+ ],
330
+ sessions: [...imported.sessions.values()].map((source) => parsePiSession(source).header.id),
331
+ };
332
+ },
333
+ };
334
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./exchange.js";
2
+ export * from "./sessions.js";
3
+ export * from "./directory.js";
4
+ export * from "./host.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./exchange.js";
2
+ export * from "./sessions.js";
3
+ export * from "./directory.js";
4
+ export * from "./host.js";
@@ -0,0 +1,12 @@
1
+ import { type Citation, type ExactPatchRef, type Material, type MetadataValue, type ModeEntry, type NodeId, type SemanticOperation, type SurfaceId, type ObjectId } from "@mmon-co/ncept-core";
2
+ export declare function nonempty(value: unknown): value is string;
3
+ export declare function isSurface(value: unknown): value is SurfaceId;
4
+ export declare function isObjectIdentity(value: unknown): value is ObjectId;
5
+ export declare function nodeIds(value: unknown): readonly NodeId[];
6
+ export declare function exactRef(value: unknown): ExactPatchRef;
7
+ export declare function metadataProperties(value: unknown): Readonly<Record<string, MetadataValue>>;
8
+ export declare function isMaterial(value: unknown): value is Material;
9
+ export declare function operations(value: unknown): readonly SemanticOperation[];
10
+ export declare function citations(value: unknown): readonly Citation[];
11
+ export declare function strings(value: unknown): readonly string[];
12
+ export declare function modeEntry(value: unknown): ModeEntry;