@seed-hypermedia/client 0.0.122 → 0.0.123

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/dist/apps.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Apps and tools: documents typed `hm://hyper.media/app` and `hm://hyper.media/tool`.
2
+ * Apps and their children: documents typed `hm://hyper.media/app`, `hm://hyper.media/tool`,
3
+ * `hm://hyper.media/page` and `hm://hyper.media/trigger`.
3
4
  *
4
5
  * An app lists its children (tools and custom HTML pages) as card embeds in its content, and every
5
6
  * child lives one path segment under the app. The embeds are the source of truth for which children
@@ -15,6 +16,7 @@ export declare const HM_APP_TYPE = "hm://hyper.media/app";
15
16
  export declare const HM_TOOL_TYPE = "hm://hyper.media/tool";
16
17
  export declare const HM_PAGE_TYPE = "hm://hyper.media/page";
17
18
  export declare const HM_AGENT_TYPE = "hm://hyper.media/agent";
19
+ export declare const HM_TRIGGER_TYPE = "hm://hyper.media/trigger";
18
20
  /**
19
21
  * Documents that host tools and pages: apps and agents (the two are converging into one concept).
20
22
  * Both list their children as card embeds and run their tools the same way.
@@ -24,8 +26,8 @@ export declare function isToolHostType(type: unknown): boolean;
24
26
  export declare const TOOL_ENTRY_FILE = "index.ts";
25
27
  /** Starting code for a tool created without any. */
26
28
  export declare const TOOL_CODE_TEMPLATE = "export default async function (input) {\n return {}\n}\n";
27
- /** The kinds of children an app endorses. */
28
- export type AppChildKind = 'tool' | 'page';
29
+ /** The kinds of children an app (or agent) endorses. */
30
+ export type AppChildKind = 'tool' | 'page' | 'trigger';
29
31
  /** Which app child a document type is, or null for any other type. */
30
32
  export declare function appChildKind(type: unknown): AppChildKind | null;
31
33
  /** One child an app lists: the embed block that lists it and the child's versionless id. */
@@ -71,3 +73,46 @@ export declare function createDocumentUpdateBlobs({ client, signer, id, ops, cap
71
73
  blobs: CollectedBlob[];
72
74
  targetId: UnpackedHypermediaId;
73
75
  }>;
76
+ /**
77
+ * A trigger document (`type: hm://hyper.media/trigger`) is a child of an app or an agent, listed in
78
+ * it as a card embed like a tool. Its metadata says when it fires and what it does:
79
+ *
80
+ * - `source`: `ipfs://<cid>` of a DAG-CBOR trigger source (activity conditions, a schedule, a
81
+ * webhook, or run-completed), the same shape agents' triggers have always used.
82
+ * - `tool`: optionally the hm:// URL of one of its host's tools to call when it fires.
83
+ * - `input`: optionally `ipfs://<cid>` of a DAG-CBOR input template for that tool; string values
84
+ * `"$event"` and `"$event.<path>"` are replaced from the event.
85
+ * - `enabled`: `false` turns it off; any other value (or none) leaves it on.
86
+ *
87
+ * With no `tool`, a trigger under an agent starts a session with the agent and the trigger's body
88
+ * (its content) is the first message. A trigger under an app must name a tool.
89
+ */
90
+ export type TriggerDocumentFields = {
91
+ /** The trigger source; published as a DAG-CBOR blob. */
92
+ source: unknown;
93
+ /** hm:// URL of the host's tool to call, or null to start an agent session. */
94
+ tool?: string | null;
95
+ /** Input template for the tool; published as a DAG-CBOR blob. */
96
+ input?: unknown;
97
+ enabled?: boolean;
98
+ };
99
+ /** A trigger document's metadata as stored: references to its source and input blobs. */
100
+ export type TriggerDocumentRefs = {
101
+ sourceCid: string | null;
102
+ tool: string | null;
103
+ inputCid: string | null;
104
+ enabled: boolean;
105
+ };
106
+ /** The CID inside an `ipfs://<cid>` reference (or a bare CID), or null. */
107
+ export declare function ipfsRefCid(value: unknown): string | null;
108
+ /** Reads a trigger document's metadata references. */
109
+ export declare function triggerDocumentRefs(metadata: Record<string, unknown> | undefined): TriggerDocumentRefs;
110
+ /**
111
+ * The `SetAttributes` op that writes a trigger's fields, with the DAG-CBOR blobs it references
112
+ * (publish them with the change). Fields left `undefined` are not touched; `tool: null` and
113
+ * `input: null` clear them.
114
+ */
115
+ export declare function triggerDocumentOps(fields: Partial<TriggerDocumentFields>): Promise<{
116
+ ops: DocumentOperation[];
117
+ blobs: CollectedBlob[];
118
+ }>;
package/dist/apps.mjs CHANGED
@@ -1,3 +1,9 @@
1
+ import {
2
+ encodeDagCbor
3
+ } from "./chunk-S5FIYL5M.mjs";
4
+ import "./chunk-UBZRS3WZ.mjs";
5
+ import "./chunk-5AZOE4Q5.mjs";
6
+ import "./chunk-VWSAFDOL.mjs";
1
7
  import {
2
8
  createChange,
3
9
  createChangeOps
@@ -15,6 +21,7 @@ import {
15
21
  toAPIBlockNode
16
22
  } from "./chunk-3KLY2B27.mjs";
17
23
  import "./chunk-LVAHHQIK.mjs";
24
+ import "./chunk-3TPCJCVO.mjs";
18
25
  import "./chunk-DR3HJ6BV.mjs";
19
26
  import {
20
27
  hmIdPathToEntityQueryPath,
@@ -30,6 +37,7 @@ var HM_APP_TYPE = "hm://hyper.media/app";
30
37
  var HM_TOOL_TYPE = "hm://hyper.media/tool";
31
38
  var HM_PAGE_TYPE = "hm://hyper.media/page";
32
39
  var HM_AGENT_TYPE = "hm://hyper.media/agent";
40
+ var HM_TRIGGER_TYPE = "hm://hyper.media/trigger";
33
41
  function isToolHostType(type) {
34
42
  return type === HM_APP_TYPE || type === HM_AGENT_TYPE;
35
43
  }
@@ -41,6 +49,7 @@ var TOOL_CODE_TEMPLATE = `export default async function (input) {
41
49
  function appChildKind(type) {
42
50
  if (type === HM_TOOL_TYPE) return "tool";
43
51
  if (type === HM_PAGE_TYPE) return "page";
52
+ if (type === HM_TRIGGER_TYPE) return "trigger";
44
53
  return null;
45
54
  }
46
55
  function appEmbeddedChildren(appId, content) {
@@ -164,11 +173,45 @@ function newBlockId() {
164
173
  const bytes = crypto.getRandomValues(new Uint8Array(8));
165
174
  return Array.from(bytes, (byte) => alphabet[byte & 63]).join("");
166
175
  }
176
+ function ipfsRefCid(value) {
177
+ if (typeof value !== "string" || !value) return null;
178
+ const cid = value.replace(/^ipfs:\/\//i, "").split("/")[0] ?? "";
179
+ return cid || null;
180
+ }
181
+ function triggerDocumentRefs(metadata) {
182
+ return {
183
+ sourceCid: ipfsRefCid(metadata == null ? void 0 : metadata.source),
184
+ tool: typeof (metadata == null ? void 0 : metadata.tool) === "string" && metadata.tool ? metadata.tool : null,
185
+ inputCid: ipfsRefCid(metadata == null ? void 0 : metadata.input),
186
+ enabled: (metadata == null ? void 0 : metadata.enabled) !== false && (metadata == null ? void 0 : metadata.enabled) !== "false"
187
+ };
188
+ }
189
+ async function triggerDocumentOps(fields) {
190
+ const attrs = [];
191
+ const blobs = [];
192
+ if (fields.source !== void 0) {
193
+ const encoded = await encodeDagCbor(fields.source);
194
+ blobs.push({ cid: encoded.cid, data: encoded.data });
195
+ attrs.push({ key: ["source"], value: `ipfs://${encoded.cid}` });
196
+ }
197
+ if (fields.tool !== void 0) attrs.push({ key: ["tool"], value: fields.tool || null });
198
+ if (fields.input !== void 0) {
199
+ if (fields.input === null) attrs.push({ key: ["input"], value: null });
200
+ else {
201
+ const encoded = await encodeDagCbor(fields.input);
202
+ blobs.push({ cid: encoded.cid, data: encoded.data });
203
+ attrs.push({ key: ["input"], value: `ipfs://${encoded.cid}` });
204
+ }
205
+ }
206
+ if (fields.enabled !== void 0) attrs.push({ key: ["enabled"], value: fields.enabled });
207
+ return { ops: attrs.length ? [{ type: "SetAttributes", attrs }] : [], blobs };
208
+ }
167
209
  export {
168
210
  HM_AGENT_TYPE,
169
211
  HM_APP_TYPE,
170
212
  HM_PAGE_TYPE,
171
213
  HM_TOOL_TYPE,
214
+ HM_TRIGGER_TYPE,
172
215
  TOOL_CODE_TEMPLATE,
173
216
  TOOL_ENTRY_FILE,
174
217
  addAppChildOps,
@@ -176,9 +219,12 @@ export {
176
219
  appChildrenOps,
177
220
  appEmbeddedChildren,
178
221
  createDocumentUpdateBlobs,
222
+ ipfsRefCid,
179
223
  isAppChildId,
180
224
  isToolHostType,
181
225
  parentDocumentId,
182
226
  removeAppChildOps,
183
- replaceContentOps
227
+ replaceContentOps,
228
+ triggerDocumentOps,
229
+ triggerDocumentRefs
184
230
  };
package/dist/auth.mjs CHANGED
@@ -14,9 +14,9 @@ import {
14
14
  parseEmailPrevalidation,
15
15
  validateClientId,
16
16
  validateRedirectUri
17
- } from "./chunk-XJ4BKTVL.mjs";
17
+ } from "./chunk-WN25ZBDL.mjs";
18
18
  import {
19
- decode,
19
+ decode as decode2,
20
20
  encode
21
21
  } from "./chunk-2MD3FXKB.mjs";
22
22
  import {
@@ -28,7 +28,7 @@ import {
28
28
  verify
29
29
  } from "./chunk-GBSWXJGU.mjs";
30
30
  import {
31
- decode as decode2
31
+ decode
32
32
  } from "./chunk-3TPCJCVO.mjs";
33
33
  import "./chunk-DR3HJ6BV.mjs";
34
34
  import "./chunk-7P6ASYW6.mjs";
@@ -197,7 +197,7 @@ async function handleCallback(config, options = {}) {
197
197
  vaultUrl: record.vaultUrl,
198
198
  createdAt: record.createTime
199
199
  };
200
- const callbackData = decode2(await decompress(decode(dataParam)));
200
+ const callbackData = decode(await decompress(decode2(dataParam)));
201
201
  let notifyServerUrl;
202
202
  if (callbackData.notifyServerUrl && typeof callbackData.notifyServerUrl === "string") {
203
203
  try {
@@ -236,7 +236,7 @@ async function handleCallback(config, options = {}) {
236
236
  let emailPrevalidation;
237
237
  if (emailProof) {
238
238
  try {
239
- emailPrevalidation = parseEmailPrevalidation(decode2(decode(emailProof)), vaultUrl);
239
+ emailPrevalidation = parseEmailPrevalidation(decode(decode2(emailProof)), vaultUrl);
240
240
  } catch {
241
241
  }
242
242
  }
@@ -7,7 +7,7 @@ import {
7
7
  emitFrontmatter,
8
8
  parseDraftFilename,
9
9
  slugify
10
- } from "./chunk-LZYLDVJR.mjs";
10
+ } from "./chunk-VWLXKOLW.mjs";
11
11
  import "./chunk-XMDF4NIR.mjs";
12
12
  import "./chunk-LOAOGLQF.mjs";
13
13
  import "./chunk-AHQWDCHV.mjs";
@@ -623,10 +623,62 @@ var IMAGE_START_RE = /^!\[/;
623
623
  function startsSpecialBlock(rest) {
624
624
  return HEADING_RE.test(rest) || FENCE_RE.test(rest) || rest.startsWith("$$") || IMAGE_START_RE.test(rest) || rest.startsWith("|") || STANDALONE_COMMENT_RE.test(rest) || END_RE.test(rest);
625
625
  }
626
+ var RESOLVED_EMBED_OPEN = /^(\s*)<!--\s*embed:\s*([^;\s]+)\s*((?:;[^>]*?)?)\s*-->\s*(?:<!--\s*id:([A-Za-z0-9_-]+)(?:\s+type:[A-Za-z0-9_-]+)?(?:\s+attrs:(\{.*\}))?\s*-->)?\s*$/;
627
+ var RESOLVED_EMBED_CLOSE = /^\s*<!--\s*\/embed:\s*([^\s]+)\s*-->\s*$/;
628
+ function collapseResolvedEmbeds(markdown) {
629
+ if (!markdown.includes("<!--") || !/<!--\s*embed:/.test(markdown)) return markdown;
630
+ const lines = markdown.split("\n");
631
+ const out = [];
632
+ let fence = null;
633
+ for (let i = 0; i < lines.length; i++) {
634
+ const line = lines[i];
635
+ const fenceMatch = /^\s*(```+|~~~+)/.exec(line);
636
+ if (fenceMatch) {
637
+ if (!fence) fence = fenceMatch[1];
638
+ else if (fenceMatch[1].startsWith(fence[0]) && fenceMatch[1].length >= fence.length) fence = null;
639
+ out.push(line);
640
+ continue;
641
+ }
642
+ const open = fence ? null : RESOLVED_EMBED_OPEN.exec(line);
643
+ if (!open) {
644
+ out.push(line);
645
+ continue;
646
+ }
647
+ const [, indent = "", link = "", rest = "", id, rawAttrs] = open;
648
+ let depth = 1;
649
+ let end = -1;
650
+ for (let j = i + 1; j < lines.length; j++) {
651
+ if (RESOLVED_EMBED_OPEN.test(lines[j])) depth++;
652
+ else if (RESOLVED_EMBED_CLOSE.test(lines[j]) && --depth === 0) {
653
+ end = j;
654
+ break;
655
+ }
656
+ }
657
+ if (end === -1) {
658
+ out.push(line);
659
+ continue;
660
+ }
661
+ const attrs = {};
662
+ if (rawAttrs) {
663
+ try {
664
+ Object.assign(attrs, JSON.parse(rawAttrs));
665
+ } catch {
666
+ }
667
+ }
668
+ for (const part of rest.split(";")) {
669
+ const m = /^\s*(view|version|block)\s*:\s*(.+?)\s*$/.exec(part);
670
+ if (m && m[1] === "view") attrs.view = m[2];
671
+ }
672
+ const comment = `<!-- id:${id || generateBlockId()} type:Embed${Object.keys(attrs).length ? ` attrs:${JSON.stringify(attrs)}` : ""} -->`;
673
+ out.push(`${indent}<${link}> ${comment}`);
674
+ i = end;
675
+ }
676
+ return out.join("\n");
677
+ }
626
678
  function parseMarkdown(markdown, options = {}) {
627
679
  var _a;
628
680
  const { content, metadata } = parseFrontmatter(markdown, options);
629
- const lines = content.split("\n");
681
+ const lines = collapseResolvedEmbeds(content).split("\n");
630
682
  const infos = lines.map(analyzeLine);
631
683
  const root = { list: [], childIndent: 0 };
632
684
  const stack = [root];
@@ -908,6 +960,7 @@ export {
908
960
  mergeAdjacentAnnotations,
909
961
  MarkdownFrontmatterError,
910
962
  parseFrontmatter,
963
+ collapseResolvedEmbeds,
911
964
  parseMarkdown,
912
965
  markdownBlockNodesToHMBlockNodes,
913
966
  flattenToOperations
@@ -0,0 +1,122 @@
1
+ import {
2
+ fieldSchema,
3
+ fieldsToProperties,
4
+ isLiteralSchema,
5
+ literalValue,
6
+ resolveSchema,
7
+ structFields
8
+ } from "./chunk-UBZRS3WZ.mjs";
9
+ import {
10
+ dagJsonToIpld,
11
+ findSeedIndexerCollision
12
+ } from "./chunk-VWSAFDOL.mjs";
13
+ import {
14
+ code,
15
+ encode
16
+ } from "./chunk-3TPCJCVO.mjs";
17
+
18
+ // src/signed-blob.ts
19
+ import { ed25519 } from "@noble/curves/ed25519.js";
20
+ import { base58btc } from "multiformats/bases/base58";
21
+ import { CID } from "multiformats/cid";
22
+ import { sha256 } from "multiformats/hashes/sha2";
23
+ var SIGNED_BLOB_ENVELOPE = ["signer", "sig", "ts"];
24
+ var ZERO_SIGNATURE_LENGTH = 64;
25
+ function isSignedBlobSchema(schema, reg = {}) {
26
+ if (!schema) return false;
27
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
28
+ const props = resolved.properties;
29
+ return !!props && SIGNED_BLOB_ENVELOPE.every((k) => fieldSchema(resolved, k) !== void 0);
30
+ }
31
+ function signedBlobTypeTag(schema, reg = {}) {
32
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
33
+ const t = fieldSchema(resolved, "type");
34
+ const tag = t !== void 0 && isLiteralSchema(t) ? literalValue(t) : void 0;
35
+ return typeof tag === "string" ? tag : void 0;
36
+ }
37
+ function stripSignedBlobEnvelope(schema, reg = {}) {
38
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
39
+ const hidden = new Set(SIGNED_BLOB_ENVELOPE);
40
+ if (signedBlobTypeTag(schema, reg)) hidden.add("type");
41
+ const { required: _legacy, ...rest } = resolved;
42
+ return { ...rest, properties: fieldsToProperties(structFields(resolved).filter((f) => !hidden.has(f.name))) };
43
+ }
44
+ function signedBlobMessage(blob) {
45
+ return new Uint8Array(encode({ ...blob, sig: new Uint8Array(ZERO_SIGNATURE_LENGTH) }));
46
+ }
47
+ async function signBlob(signer, body, opts = {}) {
48
+ const ipld = dagJsonToIpld(body);
49
+ const principal = new Uint8Array(await signer.getPublicKey());
50
+ const ts = opts.ts ?? Date.now();
51
+ const blob = { ...ipld };
52
+ if (opts.typeTag) blob.type = opts.typeTag;
53
+ blob.signer = principal;
54
+ blob.ts = ts;
55
+ blob.sig = new Uint8Array(await signer.sign(signedBlobMessage(blob)));
56
+ const data = new Uint8Array(encode(blob));
57
+ const digest = await sha256.digest(data);
58
+ return { cid: CID.createV1(code, digest).toString(), data, ts, signer: principal };
59
+ }
60
+ async function publishSignedBlob(client, signer, body, opts = {}) {
61
+ const result = await signBlob(signer, body, opts);
62
+ const collision = findSeedIndexerCollision(result.data);
63
+ if (collision) {
64
+ throw new Error(
65
+ `This blob can't be published: its "type" collides with the built-in Seed "${collision}" blob type but does not match its shape. Use a different type tag.`
66
+ );
67
+ }
68
+ await client.request("PublishBlobs", { blobs: [{ cid: result.cid, data: result.data }] });
69
+ return result;
70
+ }
71
+ function hasSignedEnvelope(value) {
72
+ return !!value && typeof value === "object" && !Array.isArray(value) && SIGNED_BLOB_ENVELOPE.every((k) => k in value);
73
+ }
74
+ function principalToPublicKey(principal) {
75
+ if (principal.length !== 34 || principal[0] !== 237 || principal[1] !== 1) {
76
+ throw new Error(
77
+ `Unsupported principal: expected an Ed25519 multicodec key (34 bytes), got ${principal.length} bytes`
78
+ );
79
+ }
80
+ return principal.slice(2);
81
+ }
82
+ async function verifySignedBlob(value) {
83
+ const ipld = dagJsonToIpld(value);
84
+ const signer = ipld.signer;
85
+ const sig = ipld.sig;
86
+ if (!(signer instanceof Uint8Array)) return { ok: false, signer: "", reason: "signer is not bytes" };
87
+ const signerId = base58btc.encode(signer);
88
+ if (!(sig instanceof Uint8Array)) return { ok: false, signer: signerId, reason: "sig is not bytes" };
89
+ let publicKey;
90
+ try {
91
+ publicKey = principalToPublicKey(signer);
92
+ } catch (error) {
93
+ return { ok: false, signer: signerId, reason: error.message };
94
+ }
95
+ const ts = typeof ipld.ts === "number" ? ipld.ts : void 0;
96
+ try {
97
+ const ok = ed25519.verify(sig, signedBlobMessage(ipld), publicKey);
98
+ return ok ? { ok, signer: signerId, ts } : { ok, signer: signerId, ts, reason: "signature does not verify" };
99
+ } catch (error) {
100
+ return { ok: false, signer: signerId, ts, reason: error.message };
101
+ }
102
+ }
103
+ async function encodeDagCbor(value) {
104
+ const data = new Uint8Array(encode(dagJsonToIpld(value)));
105
+ const digest = await sha256.digest(data);
106
+ return { data, cid: CID.createV1(code, digest).toString() };
107
+ }
108
+
109
+ export {
110
+ SIGNED_BLOB_ENVELOPE,
111
+ ZERO_SIGNATURE_LENGTH,
112
+ isSignedBlobSchema,
113
+ signedBlobTypeTag,
114
+ stripSignedBlobEnvelope,
115
+ signedBlobMessage,
116
+ signBlob,
117
+ publishSignedBlob,
118
+ hasSignedEnvelope,
119
+ principalToPublicKey,
120
+ verifySignedBlob,
121
+ encodeDagCbor
122
+ };
@@ -585,7 +585,7 @@ async function resolvedBlockToMarkdown(block, depth, ctx) {
585
585
  }
586
586
  }
587
587
  async function resolveBlockEmbed(block, depth, ctx) {
588
- var _a;
588
+ var _a, _b;
589
589
  const ind = resolvedIndent(depth);
590
590
  const link = block.link || "";
591
591
  if (ctx.currentDepth >= ctx.maxDepth) return ind + `> [Embed: ${link}](${link})`;
@@ -598,6 +598,8 @@ async function resolveBlockEmbed(block, depth, ctx) {
598
598
  if (!content.length) return ind + `> [Embed: ${resolved.label}](${link})`;
599
599
  const lines = [];
600
600
  const metadata = [`embed: ${link}`, `title: ${resolved.label}`];
601
+ const view = (_b = block.attributes) == null ? void 0 : _b.view;
602
+ if (typeof view === "string" && view) metadata.push(`view: ${view}`);
601
603
  if (id.version) metadata.push(`version: ${id.version}`);
602
604
  if (id.blockRef) metadata.push(`block: ${id.blockRef}${formatBlockRange(id)}`);
603
605
  lines.push(ind + `<!-- ${metadata.join("; ")} -->`);
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  decode,
3
- encode
3
+ encode as encode2
4
4
  } from "./chunk-2MD3FXKB.mjs";
5
5
  import {
6
6
  ED25519_VARINT_PREFIX,
@@ -10,7 +10,7 @@ import {
10
10
  principalToString
11
11
  } from "./chunk-GBSWXJGU.mjs";
12
12
  import {
13
- encode as encode2
13
+ encode
14
14
  } from "./chunk-3TPCJCVO.mjs";
15
15
 
16
16
  // src/hmauth.ts
@@ -270,9 +270,9 @@ async function buildCallbackUrl(redirectUri, state, accountPrincipal, capability
270
270
  profileCid: profile.cid,
271
271
  ...notifyServerUrl ? { notifyServerUrl } : {}
272
272
  };
273
- const encodedCbor = encode2(callbackData);
273
+ const encodedCbor = encode(callbackData);
274
274
  const compressed = await compress(new Uint8Array(encodedCbor));
275
- url.searchParams.set(PARAM_DATA, encode(compressed));
275
+ url.searchParams.set(PARAM_DATA, encode2(compressed));
276
276
  url.searchParams.set(PARAM_STATE, state);
277
277
  return url.toString();
278
278
  }
package/dist/hmauth.mjs CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  validateSessionKeyPrincipal,
25
25
  validateState,
26
26
  verifyDelegationRequestProof
27
- } from "./chunk-XJ4BKTVL.mjs";
27
+ } from "./chunk-WN25ZBDL.mjs";
28
28
  import "./chunk-2MD3FXKB.mjs";
29
29
  import "./chunk-GBSWXJGU.mjs";
30
30
  import "./chunk-3TPCJCVO.mjs";
package/dist/index.mjs CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  parseFrontmatter,
27
27
  parseInlineFormatting,
28
28
  parseMarkdown
29
- } from "./chunk-KKKXGVKJ.mjs";
29
+ } from "./chunk-4WRPNPEJ.mjs";
30
30
  import {
31
31
  InvalidMermaidError,
32
32
  assertValidMermaid,
@@ -129,7 +129,7 @@ import {
129
129
  emitFrontmatter,
130
130
  parseDraftFilename,
131
131
  slugify
132
- } from "./chunk-LZYLDVJR.mjs";
132
+ } from "./chunk-VWLXKOLW.mjs";
133
133
  import {
134
134
  extractCommentIdFromUrl,
135
135
  hmDomainUrlToWebUrl,
@@ -92,12 +92,14 @@ export declare function parseFrontmatter(markdown: string, options?: ParseMarkdo
92
92
  metadata: HMMetadata;
93
93
  };
94
94
  /**
95
- * Builds a hierarchical block tree from markdown.
96
- *
97
- * See the module header for the dialect. Frontmatter is parsed for document
98
- * metadata and stripped from the content before tokenizing. Block IDs from
99
- * `<!-- id:… -->` comments are preserved; absent ids are generated.
95
+ * Turns each resolved embed back into the embed it came from. Resolved markdown (what an agent's
96
+ * `read` returns) prints an embed as its target's content between `<!-- embed: URL; title: …;
97
+ * view: … -->` and `<!-- /embed: URL -->`. Written back, that range must become the Embed block
98
+ * again, not paragraphs copied out of the embedded document, so a read-then-write round trip keeps
99
+ * the document's embeds. Nested embeds inside the range belong to the embedded document and go
100
+ * with it. Lines inside code fences are left alone.
100
101
  */
102
+ export declare function collapseResolvedEmbeds(markdown: string): string;
101
103
  export declare function parseMarkdown(markdown: string, options?: ParseMarkdownOptions): {
102
104
  tree: BlockNode[];
103
105
  metadata: HMMetadata;
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  MarkdownFrontmatterError,
3
+ collapseResolvedEmbeds,
3
4
  flattenToOperations,
4
5
  hmAccountMentionUid,
5
6
  markdownBlockNodesToHMBlockNodes,
@@ -7,10 +8,11 @@ import {
7
8
  parseFrontmatter,
8
9
  parseInlineFormatting,
9
10
  parseMarkdown
10
- } from "./chunk-KKKXGVKJ.mjs";
11
+ } from "./chunk-4WRPNPEJ.mjs";
11
12
  import "./chunk-7P6ASYW6.mjs";
12
13
  export {
13
14
  MarkdownFrontmatterError,
15
+ collapseResolvedEmbeds,
14
16
  flattenToOperations,
15
17
  hmAccountMentionUid,
16
18
  markdownBlockNodesToHMBlockNodes,
@@ -1,112 +1,22 @@
1
1
  import {
2
- fieldSchema,
3
- fieldsToProperties,
4
- isLiteralSchema,
5
- literalValue,
6
- resolveSchema,
7
- structFields
8
- } from "./chunk-UBZRS3WZ.mjs";
2
+ SIGNED_BLOB_ENVELOPE,
3
+ ZERO_SIGNATURE_LENGTH,
4
+ encodeDagCbor,
5
+ hasSignedEnvelope,
6
+ isSignedBlobSchema,
7
+ principalToPublicKey,
8
+ publishSignedBlob,
9
+ signBlob,
10
+ signedBlobMessage,
11
+ signedBlobTypeTag,
12
+ stripSignedBlobEnvelope,
13
+ verifySignedBlob
14
+ } from "./chunk-S5FIYL5M.mjs";
15
+ import "./chunk-UBZRS3WZ.mjs";
9
16
  import "./chunk-5AZOE4Q5.mjs";
10
- import {
11
- dagJsonToIpld,
12
- findSeedIndexerCollision
13
- } from "./chunk-VWSAFDOL.mjs";
14
- import {
15
- code,
16
- encode
17
- } from "./chunk-3TPCJCVO.mjs";
17
+ import "./chunk-VWSAFDOL.mjs";
18
+ import "./chunk-3TPCJCVO.mjs";
18
19
  import "./chunk-7P6ASYW6.mjs";
19
-
20
- // src/signed-blob.ts
21
- import { ed25519 } from "@noble/curves/ed25519.js";
22
- import { base58btc } from "multiformats/bases/base58";
23
- import { CID } from "multiformats/cid";
24
- import { sha256 } from "multiformats/hashes/sha2";
25
- var SIGNED_BLOB_ENVELOPE = ["signer", "sig", "ts"];
26
- var ZERO_SIGNATURE_LENGTH = 64;
27
- function isSignedBlobSchema(schema, reg = {}) {
28
- if (!schema) return false;
29
- const { schema: resolved } = resolveSchema(schema, {}, reg);
30
- const props = resolved.properties;
31
- return !!props && SIGNED_BLOB_ENVELOPE.every((k) => fieldSchema(resolved, k) !== void 0);
32
- }
33
- function signedBlobTypeTag(schema, reg = {}) {
34
- const { schema: resolved } = resolveSchema(schema, {}, reg);
35
- const t = fieldSchema(resolved, "type");
36
- const tag = t !== void 0 && isLiteralSchema(t) ? literalValue(t) : void 0;
37
- return typeof tag === "string" ? tag : void 0;
38
- }
39
- function stripSignedBlobEnvelope(schema, reg = {}) {
40
- const { schema: resolved } = resolveSchema(schema, {}, reg);
41
- const hidden = new Set(SIGNED_BLOB_ENVELOPE);
42
- if (signedBlobTypeTag(schema, reg)) hidden.add("type");
43
- const { required: _legacy, ...rest } = resolved;
44
- return { ...rest, properties: fieldsToProperties(structFields(resolved).filter((f) => !hidden.has(f.name))) };
45
- }
46
- function signedBlobMessage(blob) {
47
- return new Uint8Array(encode({ ...blob, sig: new Uint8Array(ZERO_SIGNATURE_LENGTH) }));
48
- }
49
- async function signBlob(signer, body, opts = {}) {
50
- const ipld = dagJsonToIpld(body);
51
- const principal = new Uint8Array(await signer.getPublicKey());
52
- const ts = opts.ts ?? Date.now();
53
- const blob = { ...ipld };
54
- if (opts.typeTag) blob.type = opts.typeTag;
55
- blob.signer = principal;
56
- blob.ts = ts;
57
- blob.sig = new Uint8Array(await signer.sign(signedBlobMessage(blob)));
58
- const data = new Uint8Array(encode(blob));
59
- const digest = await sha256.digest(data);
60
- return { cid: CID.createV1(code, digest).toString(), data, ts, signer: principal };
61
- }
62
- async function publishSignedBlob(client, signer, body, opts = {}) {
63
- const result = await signBlob(signer, body, opts);
64
- const collision = findSeedIndexerCollision(result.data);
65
- if (collision) {
66
- throw new Error(
67
- `This blob can't be published: its "type" collides with the built-in Seed "${collision}" blob type but does not match its shape. Use a different type tag.`
68
- );
69
- }
70
- await client.request("PublishBlobs", { blobs: [{ cid: result.cid, data: result.data }] });
71
- return result;
72
- }
73
- function hasSignedEnvelope(value) {
74
- return !!value && typeof value === "object" && !Array.isArray(value) && SIGNED_BLOB_ENVELOPE.every((k) => k in value);
75
- }
76
- function principalToPublicKey(principal) {
77
- if (principal.length !== 34 || principal[0] !== 237 || principal[1] !== 1) {
78
- throw new Error(
79
- `Unsupported principal: expected an Ed25519 multicodec key (34 bytes), got ${principal.length} bytes`
80
- );
81
- }
82
- return principal.slice(2);
83
- }
84
- async function verifySignedBlob(value) {
85
- const ipld = dagJsonToIpld(value);
86
- const signer = ipld.signer;
87
- const sig = ipld.sig;
88
- if (!(signer instanceof Uint8Array)) return { ok: false, signer: "", reason: "signer is not bytes" };
89
- const signerId = base58btc.encode(signer);
90
- if (!(sig instanceof Uint8Array)) return { ok: false, signer: signerId, reason: "sig is not bytes" };
91
- let publicKey;
92
- try {
93
- publicKey = principalToPublicKey(signer);
94
- } catch (error) {
95
- return { ok: false, signer: signerId, reason: error.message };
96
- }
97
- const ts = typeof ipld.ts === "number" ? ipld.ts : void 0;
98
- try {
99
- const ok = ed25519.verify(sig, signedBlobMessage(ipld), publicKey);
100
- return ok ? { ok, signer: signerId, ts } : { ok, signer: signerId, ts, reason: "signature does not verify" };
101
- } catch (error) {
102
- return { ok: false, signer: signerId, ts, reason: error.message };
103
- }
104
- }
105
- async function encodeDagCbor(value) {
106
- const data = new Uint8Array(encode(dagJsonToIpld(value)));
107
- const digest = await sha256.digest(data);
108
- return { data, cid: CID.createV1(code, digest).toString() };
109
- }
110
20
  export {
111
21
  SIGNED_BLOB_ENVELOPE,
112
22
  ZERO_SIGNATURE_LENGTH,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seed-hypermedia/client",
3
- "version": "0.0.122",
3
+ "version": "0.0.123",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/seed-hypermedia/seed",