@seed-hypermedia/client 0.0.122 → 0.0.124

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,52 @@ 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 holds the whole trigger, readable and editable in
79
+ * place:
80
+ *
81
+ * - `source`: when it fires (activity conditions, a schedule, a webhook, or a run finishing).
82
+ * - `tool`: optionally the hm:// URL of one of its host's tools to call when it fires.
83
+ * - `input`: optionally the tool's input template; string values `"$event"` and `"$event.<path>"`
84
+ * 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 calls one of the app's tools.
89
+ *
90
+ * Document attributes merge key by key, and a list is one value that can only be replaced whole, so
91
+ * the source stores its sets as maps (see {@link triggerSourceToMetadata}): `daysOfWeek: {mon: true}`,
92
+ * `timesOfDay: {"08:00": true}`, account lists as `{<account>: true}`, `eventTypes: {comment: true}`,
93
+ * and `conditions` keyed by their ids. Each entry is then its own key, edited without touching the
94
+ * others.
95
+ */
96
+ export type TriggerDocumentFields = {
97
+ /** The trigger source, in the engine's shape (lists); stored as maps. */
98
+ source: unknown;
99
+ /** hm:// URL of the host's tool to call, or null to start an agent session. */
100
+ tool?: string | null;
101
+ /** Input template for the tool. */
102
+ input?: unknown;
103
+ enabled?: boolean;
104
+ };
105
+ /** A trigger source as document metadata: its lists as maps, so each entry is its own key. */
106
+ export declare function triggerSourceToMetadata(source: unknown): unknown;
107
+ /** A trigger source read from document metadata, in the engine's shape. */
108
+ export declare function triggerSourceFromMetadata(metadata: unknown): unknown;
109
+ /** A trigger document's fields, read from its metadata. */
110
+ export declare function triggerDocumentFields(metadata: Record<string, unknown> | undefined): {
111
+ source: unknown;
112
+ tool: string | null;
113
+ input: unknown;
114
+ enabled: boolean;
115
+ };
116
+ /**
117
+ * The `SetAttributes` op that writes a trigger's fields into its document. Fields left `undefined`
118
+ * are not touched; `tool: null` and `input: null` clear them. A field that is written replaces what
119
+ * was there: it is cleared first, then set entry by entry.
120
+ */
121
+ export declare function triggerDocumentOps(fields: Partial<TriggerDocumentFields>): Promise<{
122
+ ops: DocumentOperation[];
123
+ blobs: CollectedBlob[];
124
+ }>;
package/dist/apps.mjs CHANGED
@@ -30,6 +30,7 @@ var HM_APP_TYPE = "hm://hyper.media/app";
30
30
  var HM_TOOL_TYPE = "hm://hyper.media/tool";
31
31
  var HM_PAGE_TYPE = "hm://hyper.media/page";
32
32
  var HM_AGENT_TYPE = "hm://hyper.media/agent";
33
+ var HM_TRIGGER_TYPE = "hm://hyper.media/trigger";
33
34
  function isToolHostType(type) {
34
35
  return type === HM_APP_TYPE || type === HM_AGENT_TYPE;
35
36
  }
@@ -41,6 +42,7 @@ var TOOL_CODE_TEMPLATE = `export default async function (input) {
41
42
  function appChildKind(type) {
42
43
  if (type === HM_TOOL_TYPE) return "tool";
43
44
  if (type === HM_PAGE_TYPE) return "page";
45
+ if (type === HM_TRIGGER_TYPE) return "trigger";
44
46
  return null;
45
47
  }
46
48
  function appEmbeddedChildren(appId, content) {
@@ -164,11 +166,81 @@ function newBlockId() {
164
166
  const bytes = crypto.getRandomValues(new Uint8Array(8));
165
167
  return Array.from(bytes, (byte) => alphabet[byte & 63]).join("");
166
168
  }
169
+ var DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
170
+ var SET_FIELDS = ["timesOfDay", "mentionedAccounts", "repliedToAccounts", "documentAuthors", "eventTypes"];
171
+ function isPlainRecord(value) {
172
+ return !!value && typeof value === "object" && !Array.isArray(value);
173
+ }
174
+ function triggerSourceToMetadata(source) {
175
+ if (!isPlainRecord(source)) return source;
176
+ const out = {};
177
+ for (const [key, value] of Object.entries(source)) {
178
+ if (key === "daysOfWeek" && Array.isArray(value))
179
+ out[key] = Object.fromEntries(value.map((day) => [DAY_NAMES[Number(day)] ?? String(day), true]));
180
+ else if (SET_FIELDS.includes(key) && Array.isArray(value))
181
+ out[key] = Object.fromEntries(value.map((item) => [String(item), true]));
182
+ else if (key === "conditions" && Array.isArray(value))
183
+ out[key] = Object.fromEntries(
184
+ value.map((condition, index) => {
185
+ const { id, source: conditionSource } = condition ?? {};
186
+ return [
187
+ typeof id === "string" && id ? id : `condition-${index + 1}`,
188
+ triggerSourceToMetadata(conditionSource)
189
+ ];
190
+ })
191
+ );
192
+ else out[key] = isPlainRecord(value) ? triggerSourceToMetadata(value) : value;
193
+ }
194
+ return out;
195
+ }
196
+ function triggerSourceFromMetadata(metadata) {
197
+ if (!isPlainRecord(metadata)) return metadata;
198
+ const members = (value) => isPlainRecord(value) ? Object.entries(value).filter(([, on]) => on === true || on === "true").map(([item]) => item) : Array.isArray(value) ? value : [];
199
+ const out = {};
200
+ for (const [key, value] of Object.entries(metadata)) {
201
+ if (key === "daysOfWeek")
202
+ out[key] = members(value).map((day) => typeof day === "number" ? day : DAY_NAMES.indexOf(String(day).toLowerCase())).filter((day) => day >= 0).sort((a, b) => a - b);
203
+ else if (SET_FIELDS.includes(key)) out[key] = key === "timesOfDay" ? members(value).sort() : members(value);
204
+ else if (key === "conditions" && isPlainRecord(value))
205
+ out[key] = Object.entries(value).map(([id, condition]) => ({ id, source: triggerSourceFromMetadata(condition) }));
206
+ else out[key] = isPlainRecord(value) ? triggerSourceFromMetadata(value) : value;
207
+ }
208
+ return out;
209
+ }
210
+ function triggerDocumentFields(metadata) {
211
+ return {
212
+ source: isPlainRecord(metadata == null ? void 0 : metadata.source) ? triggerSourceFromMetadata(metadata.source) : void 0,
213
+ tool: typeof (metadata == null ? void 0 : metadata.tool) === "string" && metadata.tool ? metadata.tool : null,
214
+ input: (metadata == null ? void 0 : metadata.input) ?? void 0,
215
+ enabled: (metadata == null ? void 0 : metadata.enabled) !== false && (metadata == null ? void 0 : metadata.enabled) !== "false"
216
+ };
217
+ }
218
+ function leafAttributes(key, value) {
219
+ if (!isPlainRecord(value)) return [{ key, value }];
220
+ const leaves = Object.entries(value).flatMap(([child, childValue]) => leafAttributes([...key, child], childValue));
221
+ return leaves;
222
+ }
223
+ async function triggerDocumentOps(fields) {
224
+ const attrs = [];
225
+ const replace = (key, value) => {
226
+ attrs.push({ key: [key], value: null });
227
+ if (value !== null) attrs.push(...leafAttributes([key], value));
228
+ };
229
+ if (fields.source !== void 0) replace("source", triggerSourceToMetadata(fields.source));
230
+ if (fields.tool !== void 0) attrs.push({ key: ["tool"], value: fields.tool || null });
231
+ if (fields.input !== void 0) replace("input", fields.input);
232
+ if (fields.enabled !== void 0) attrs.push({ key: ["enabled"], value: fields.enabled });
233
+ return {
234
+ ops: attrs.length ? [{ type: "SetAttributes", attrs }] : [],
235
+ blobs: []
236
+ };
237
+ }
167
238
  export {
168
239
  HM_AGENT_TYPE,
169
240
  HM_APP_TYPE,
170
241
  HM_PAGE_TYPE,
171
242
  HM_TOOL_TYPE,
243
+ HM_TRIGGER_TYPE,
172
244
  TOOL_CODE_TEMPLATE,
173
245
  TOOL_ENTRY_FILE,
174
246
  addAppChildOps,
@@ -180,5 +252,9 @@ export {
180
252
  isToolHostType,
181
253
  parentDocumentId,
182
254
  removeAppChildOps,
183
- replaceContentOps
255
+ replaceContentOps,
256
+ triggerDocumentFields,
257
+ triggerDocumentOps,
258
+ triggerSourceFromMetadata,
259
+ triggerSourceToMetadata
184
260
  };
@@ -4,7 +4,7 @@ import {
4
4
  documentContainsLinkToChild,
5
5
  documentHasSelfQuery,
6
6
  shouldAutoLinkParent
7
- } from "./chunk-CBCMOIFJ.mjs";
7
+ } from "./chunk-4OSIHGZS.mjs";
8
8
  import "./chunk-O5MHN2EO.mjs";
9
9
  import "./chunk-PJ2RFT5A.mjs";
10
10
  import "./chunk-QTPHQIZJ.mjs";
@@ -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";
@@ -69,6 +69,7 @@ function documentHasSelfQuery(document, documentId) {
69
69
  return searchBlocks(document.content || []);
70
70
  }
71
71
  function shouldAutoLinkParent(isPrivate, parentDocument, editableLocation, parentId) {
72
+ var _a;
72
73
  if (isPrivate) return false;
73
74
  if (parentDocument) {
74
75
  if (documentContainsLinkToChild(parentDocument, editableLocation)) {
@@ -77,6 +78,9 @@ function shouldAutoLinkParent(isPrivate, parentDocument, editableLocation, paren
77
78
  if (documentHasSelfQuery(parentDocument, parentId)) {
78
79
  return false;
79
80
  }
81
+ if ((_a = parentDocument.metadata) == null ? void 0 : _a.childAttributesSchema) {
82
+ return false;
83
+ }
80
84
  }
81
85
  return true;
82
86
  }
@@ -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
@@ -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("; ")} -->`);
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,
@@ -88,7 +88,7 @@ import {
88
88
  documentContainsLinkToChild,
89
89
  documentHasSelfQuery,
90
90
  shouldAutoLinkParent
91
- } from "./chunk-CBCMOIFJ.mjs";
91
+ } from "./chunk-4OSIHGZS.mjs";
92
92
  import {
93
93
  createChange,
94
94
  createChangeOps,
@@ -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,
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.124",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/seed-hypermedia/seed",