applesauce-actions 0.0.0-next-20250313155042 → 0.0.0-next-20250314133024

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/README.md CHANGED
@@ -1 +1,5 @@
1
1
  # Applesauce Actions
2
+
3
+ A collection of pre-built actions nostr clients can use. built on top of `applesauce-core` and `applesauce-factory`
4
+
5
+ [Documentation](https://hzrd149.github.io/applesauce/typedoc/modules/applesauce_actions.html)
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import { from, Subject } from "rxjs";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { subscribeSpyTo } from "@hirez_io/observer-spy";
4
+ import { EventFactory } from "applesauce-factory";
5
+ import { EventStore } from "applesauce-core";
6
+ import { FakeUser } from "./fake-user.js";
7
+ import { ActionHub } from "../action-hub.js";
8
+ import { CreateProfile } from "../actions/profile.js";
9
+ const user = new FakeUser();
10
+ const events = new EventStore();
11
+ const factory = new EventFactory({ signer: user });
12
+ describe("runAction", () => {
13
+ it("should handle action that return observables", async () => {
14
+ const e = [user.note(), user.profile({ name: "testing" })];
15
+ const action = () => from(e);
16
+ const spy = subscribeSpyTo(ActionHub.runAction({ events, factory, self: await user.getPublicKey() }, action));
17
+ await spy.onComplete();
18
+ expect(spy.getValues()).toEqual(e);
19
+ });
20
+ it("should handle action that return AsyncIterable", async () => {
21
+ const e = [user.note(), user.profile({ name: "testing" })];
22
+ async function* action() {
23
+ for (const event of e)
24
+ yield event;
25
+ }
26
+ const spy = subscribeSpyTo(ActionHub.runAction({ events, factory, self: await user.getPublicKey() }, action));
27
+ await spy.onComplete();
28
+ expect(spy.getValues()).toEqual(e);
29
+ });
30
+ it("should handle action that return Iterable", async () => {
31
+ const e = [user.note(), user.profile({ name: "testing" })];
32
+ function* action() {
33
+ for (const event of e)
34
+ yield event;
35
+ }
36
+ const spy = subscribeSpyTo(ActionHub.runAction({ events, factory, self: await user.getPublicKey() }, action));
37
+ await spy.onComplete();
38
+ expect(spy.getValues()).toEqual(e);
39
+ });
40
+ });
41
+ describe("run", () => {
42
+ it("should throw if publish is not set", async () => {
43
+ const hub = new ActionHub(events, factory);
44
+ await expect(async () => hub.run(CreateProfile, { name: "fiatjaf" })).rejects.toThrow();
45
+ });
46
+ it("should call publish with all events", async () => {
47
+ const publish = vi.fn().mockResolvedValue(undefined);
48
+ const hub = new ActionHub(events, factory, publish);
49
+ await hub.run(CreateProfile, { name: "fiatjaf" });
50
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ content: JSON.stringify({ name: "fiatjaf" }) }));
51
+ });
52
+ });
53
+ describe("exec", () => {
54
+ it("should support forEach to stream to publish", async () => {
55
+ const publish = vi.fn().mockResolvedValue(undefined);
56
+ const hub = new ActionHub(events, factory);
57
+ await hub.exec(CreateProfile, { name: "fiatjaf" }).forEach(publish);
58
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ content: JSON.stringify({ name: "fiatjaf" }) }));
59
+ });
60
+ it("should support streaming to a publish subject", async () => {
61
+ const publish = new Subject();
62
+ const spy = subscribeSpyTo(publish);
63
+ const hub = new ActionHub(events, factory);
64
+ await hub.exec(CreateProfile, { name: "fiatjaf" }).forEach((v) => publish.next(v));
65
+ expect(spy.getValues()).toEqual([expect.objectContaining({ content: JSON.stringify({ name: "fiatjaf" }) })]);
66
+ });
67
+ });
@@ -1,11 +1,12 @@
1
+ import { Observable } from "rxjs";
2
+ import { NostrEvent } from "nostr-tools";
1
3
  import { IEventStore } from "applesauce-core/event-store";
2
4
  import { EventFactory } from "applesauce-factory";
3
- import { NostrEvent } from "nostr-tools";
4
5
  /**
5
6
  * A callback used to tell the upstream app to publish an event
6
7
  * @param label a label describing what
7
8
  */
8
- export type PublishMethod = (label: string, event: NostrEvent, explicitRelays?: string[]) => Promise<void>;
9
+ export type PublishMethod = (event: NostrEvent) => void | Promise<void>;
9
10
  /** The context that is passed to actions for them to use to preform actions */
10
11
  export type ActionContext = {
11
12
  /** The event store to load events from */
@@ -14,21 +15,22 @@ export type ActionContext = {
14
15
  self: string;
15
16
  /** The event factory used to build and modify events */
16
17
  factory: EventFactory;
17
- /** A method used to publish final events to relays */
18
- publish: PublishMethod;
19
18
  };
20
19
  /** An action that can be run in a context to preform an action */
21
- export type Action<T extends unknown = unknown> = (ctx: ActionContext) => Promise<T>;
22
- export type ActionConstructor<Args extends Array<any>, T extends unknown = unknown> = (...args: Args) => Action<T>;
20
+ export type Action = (ctx: ActionContext) => Observable<NostrEvent> | AsyncGenerator<NostrEvent> | Generator<NostrEvent>;
21
+ export type ActionConstructor<Args extends Array<any>> = (...args: Args) => Action;
23
22
  /** The main class that runs actions */
24
23
  export declare class ActionHub {
25
24
  events: IEventStore;
26
25
  factory: EventFactory;
27
- publish: PublishMethod;
28
- constructor(events: IEventStore, factory: EventFactory, publish: PublishMethod);
26
+ publish?: PublishMethod | undefined;
27
+ constructor(events: IEventStore, factory: EventFactory, publish?: PublishMethod | undefined);
29
28
  protected context: ActionContext | undefined;
30
- getContext(): Promise<ActionContext>;
31
- run<Args extends Array<any>, T extends unknown = unknown>(Action: ActionConstructor<Args, T>, ...args: Args): Promise<T>;
32
- follow(pubkey: string): Promise<unknown>;
33
- unfollow(pubkey: string): Promise<unknown>;
29
+ protected getContext(): Promise<ActionContext>;
30
+ /** Runs an action in a ActionContext and converts the result to an Observable */
31
+ static runAction(ctx: ActionContext, action: Action): Observable<NostrEvent>;
32
+ /** Run an action and publish events using the publish method */
33
+ run<Args extends Array<any>>(Action: ActionConstructor<Args>, ...args: Args): Promise<void>;
34
+ /** Run an action without publishing the events */
35
+ exec<Args extends Array<any>>(Action: ActionConstructor<Args>, ...args: Args): Observable<NostrEvent>;
34
36
  }
@@ -1,4 +1,4 @@
1
- import { FollowUser } from "./actions/contacts.js";
1
+ import { from, isObservable, lastValueFrom, switchMap, toArray } from "rxjs";
2
2
  /** The main class that runs actions */
3
3
  export class ActionHub {
4
4
  events;
@@ -17,20 +17,33 @@ export class ActionHub {
17
17
  if (!this.factory.context.signer)
18
18
  throw new Error("Missing signer");
19
19
  const self = await this.factory.context.signer.getPublicKey();
20
- this.context = { self, events: this.events, factory: this.factory, publish: this.publish };
20
+ this.context = { self, events: this.events, factory: this.factory };
21
21
  return this.context;
22
22
  }
23
23
  }
24
- async run(Action, ...args) {
25
- const action = Action(...args);
26
- const ctx = await this.getContext();
27
- return await action(ctx);
24
+ /** Runs an action in a ActionContext and converts the result to an Observable */
25
+ static runAction(ctx, action) {
26
+ const result = action(ctx);
27
+ if (isObservable(result))
28
+ return result;
29
+ else
30
+ return from(result);
28
31
  }
29
- // helper methods
30
- follow(pubkey) {
31
- return this.run(FollowUser, pubkey);
32
+ /** Run an action and publish events using the publish method */
33
+ async run(Action, ...args) {
34
+ if (!this.publish)
35
+ throw new Error("Missing publish method, use ActionHub.exec");
36
+ // wait for action to complete and group events
37
+ const events = await lastValueFrom(this.exec(Action, ...args).pipe(toArray()));
38
+ // publish events
39
+ for (const event of events)
40
+ await this.publish(event);
32
41
  }
33
- unfollow(pubkey) {
34
- return this.run(FollowUser, pubkey);
42
+ /** Run an action without publishing the events */
43
+ exec(Action, ...args) {
44
+ return from(this.getContext()).pipe(switchMap((ctx) => {
45
+ const action = Action(...args);
46
+ return ActionHub.runAction(ctx, action);
47
+ }));
35
48
  }
36
49
  }
@@ -19,6 +19,6 @@ beforeEach(() => {
19
19
  describe("CreateBookmarkList", () => {
20
20
  it("should publish a kind 10003 bookmark list", async () => {
21
21
  await hub.run(CreateBookmarkList);
22
- expect(publish).toBeCalledWith(expect.any(String), expect.objectContaining({ kind: kinds.BookmarkList }));
22
+ expect(publish).toBeCalledWith(expect.objectContaining({ kind: kinds.BookmarkList }));
23
23
  });
24
24
  });
@@ -24,7 +24,7 @@ describe("FollowUser", () => {
24
24
  it('should publish an event with a new "p" tag', async () => {
25
25
  events.add(user.contacts());
26
26
  await hub.run(FollowUser, user.pubkey);
27
- expect(publish).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ tags: expect.arrayContaining([["p", user.pubkey]]) }));
27
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ tags: expect.arrayContaining([["p", user.pubkey]]) }));
28
28
  });
29
29
  });
30
30
  describe("UnfollowUser", () => {
@@ -36,7 +36,7 @@ describe("UnfollowUser", () => {
36
36
  it('should publish an event with a new "p" tag', async () => {
37
37
  events.add(user.contacts([user.pubkey]));
38
38
  await hub.run(UnfollowUser, user.pubkey);
39
- expect(publish).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ kind: 3, tags: [] }));
39
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ kind: 3, tags: [] }));
40
40
  });
41
41
  });
42
42
  describe("NewContacts", () => {
@@ -48,6 +48,6 @@ describe("NewContacts", () => {
48
48
  it("should publish a new contact event with pubkeys", async () => {
49
49
  await hub.run(NewContacts, [user.pubkey]);
50
50
  expect(publish).toHaveBeenCalled();
51
- expect(publish).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ kind: 3, tags: expect.arrayContaining([["p", user.pubkey]]) }));
51
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ kind: 3, tags: expect.arrayContaining([["p", user.pubkey]]) }));
52
52
  });
53
53
  });
@@ -1,5 +1,4 @@
1
1
  import { kinds } from "nostr-tools";
2
- import { isReplaceable } from "applesauce-core/helpers";
3
2
  import { addEventBookmarkTag, removeEventBookmarkTag } from "applesauce-factory/operations/tag";
4
3
  import { modifyHiddenTags, modifyPublicTags, setListDescription, setListImage, setListTitle, } from "applesauce-factory/operations/event";
5
4
  function getBookmarkEvent(events, self, identifier) {
@@ -12,13 +11,13 @@ function getBookmarkEvent(events, self, identifier) {
12
11
  * @param hidden set to true to add to hidden bookmarks
13
12
  */
14
13
  export function BookmarkEvent(event, identifier, hidden = false) {
15
- return async ({ events, factory, self, publish }) => {
14
+ return async function* ({ events, factory, self }) {
16
15
  const bookmarks = getBookmarkEvent(events, self, identifier);
17
16
  if (!bookmarks)
18
17
  throw new Error("Cant find bookmarks");
19
18
  const operation = addEventBookmarkTag(event);
20
19
  const draft = await factory.modifyTags(bookmarks, hidden ? { hidden: operation } : operation);
21
- await publish(`Bookmark ${isReplaceable(event.kind) ? "note" : "article"}`, await factory.sign(draft));
20
+ yield await factory.sign(draft);
22
21
  };
23
22
  }
24
23
  /**
@@ -28,32 +27,32 @@ export function BookmarkEvent(event, identifier, hidden = false) {
28
27
  * @param hidden set to true to remove from hidden bookmarks
29
28
  */
30
29
  export function UnbookmarkEvent(event, identifier, hidden = false) {
31
- return async ({ events, factory, self, publish }) => {
30
+ return async function* ({ events, factory, self }) {
32
31
  const bookmarks = getBookmarkEvent(events, self, identifier);
33
32
  if (!bookmarks)
34
33
  throw new Error("Cant find bookmarks");
35
34
  const operation = removeEventBookmarkTag(event);
36
35
  const draft = await factory.modifyTags(bookmarks, hidden ? { hidden: operation } : operation);
37
- await publish("Remove bookmark", await factory.sign(draft));
36
+ yield await factory.sign(draft);
38
37
  };
39
38
  }
40
39
  /** An action that creates a new bookmark list for a user */
41
40
  export function CreateBookmarkList(bookmarks) {
42
- return async ({ events, factory, self, publish }) => {
41
+ return async function* ({ events, factory, self }) {
43
42
  const existing = getBookmarkEvent(events, self);
44
43
  if (existing)
45
44
  throw new Error("Bookmark list already exists");
46
- const draft = await factory.process({ kind: kinds.BookmarkList }, bookmarks ? modifyPublicTags(...bookmarks.map(addEventBookmarkTag)) : undefined);
47
- await publish("Create bookmark list", await factory.sign(draft));
45
+ const draft = await factory.build({ kind: kinds.BookmarkList }, bookmarks ? modifyPublicTags(...bookmarks.map(addEventBookmarkTag)) : undefined);
46
+ yield await factory.sign(draft);
48
47
  };
49
48
  }
50
49
  /** An action that creates a new bookmark set for a user */
51
50
  export function CreateBookmarkSet(title, description, additional) {
52
- return async ({ events, factory, self, publish }) => {
51
+ return async function* ({ events, factory, self }) {
53
52
  const existing = getBookmarkEvent(events, self);
54
53
  if (existing)
55
54
  throw new Error("Bookmark list already exists");
56
55
  const draft = await factory.process({ kind: kinds.BookmarkList }, setListTitle(title), setListDescription(description), additional.image ? setListImage(additional.image) : undefined, additional.public ? modifyPublicTags(...additional.public.map(addEventBookmarkTag)) : undefined, additional.hidden ? modifyHiddenTags(...additional.hidden.map(addEventBookmarkTag)) : undefined);
57
- await publish("Create bookmark set", await factory.sign(draft));
56
+ yield await factory.sign(draft);
58
57
  };
59
58
  }
@@ -2,34 +2,34 @@ import { kinds } from "nostr-tools";
2
2
  import { addPubkeyTag, removePubkeyTag } from "applesauce-factory/operations/tag";
3
3
  /** An action that adds a pubkey to a users contacts event */
4
4
  export function FollowUser(pubkey, relay, hidden = false) {
5
- return async ({ events, factory, self, publish }) => {
5
+ return async function* ({ events, factory, self }) {
6
6
  const contacts = events.getReplaceable(kinds.Contacts, self);
7
7
  if (!contacts)
8
8
  throw new Error("Missing contacts event");
9
9
  const pointer = { pubkey, relays: relay ? [relay] : undefined };
10
10
  const operation = addPubkeyTag(pointer);
11
11
  const draft = await factory.modifyTags(contacts, hidden ? { hidden: operation } : operation);
12
- await publish("Update contacts", await factory.sign(draft));
12
+ yield await factory.sign(draft);
13
13
  };
14
14
  }
15
15
  /** An action that removes a pubkey from a users contacts event */
16
16
  export function UnfollowUser(pubkey, hidden = false) {
17
- return async ({ events, factory, self, publish }) => {
17
+ return async function* ({ events, factory, self }) {
18
18
  const contacts = events.getReplaceable(kinds.Contacts, self);
19
19
  if (!contacts)
20
20
  throw new Error("Missing contacts event");
21
21
  const operation = removePubkeyTag(pubkey);
22
22
  const draft = await factory.modifyTags(contacts, hidden ? { hidden: operation } : operation);
23
- await publish("Update contacts", await factory.sign(draft));
23
+ yield await factory.sign(draft);
24
24
  };
25
25
  }
26
26
  /** An action that creates a new kind 3 contacts lists, throws if a contact list already exists */
27
27
  export function NewContacts(pubkeys) {
28
- return async ({ events, factory, self, publish }) => {
28
+ return async function* ({ events, factory, self }) {
29
29
  const contacts = events.getReplaceable(kinds.Contacts, self);
30
30
  if (contacts)
31
31
  throw new Error("Contact list already exists");
32
32
  const draft = await factory.process({ kind: kinds.Contacts, tags: pubkeys?.map((p) => ["p", p]) });
33
- await publish("New contact list", await factory.sign(draft));
33
+ yield await factory.sign(draft);
34
34
  };
35
35
  }
@@ -3,31 +3,31 @@ import { addEventTag, removeEventTag } from "applesauce-factory/operations/tag";
3
3
  import { modifyPublicTags } from "applesauce-factory/operations/event";
4
4
  /** An action that pins a note to the users pin list */
5
5
  export function PinNote(note) {
6
- return async ({ events, factory, self, publish }) => {
6
+ return async function* ({ events, factory, self }) {
7
7
  const pins = events.getReplaceable(kinds.Pinlist, self);
8
8
  if (!pins)
9
9
  throw new Error("Missing pin list");
10
10
  const draft = await factory.modifyTags(pins, addEventTag(note.id));
11
- await publish("Pin note", await factory.sign(draft));
11
+ yield await factory.sign(draft);
12
12
  };
13
13
  }
14
14
  /** An action that removes an event from the users pin list */
15
15
  export function UnpinNote(note) {
16
- return async ({ events, factory, self, publish }) => {
16
+ return async function* ({ events, factory, self }) {
17
17
  const pins = events.getReplaceable(kinds.Pinlist, self);
18
18
  if (!pins)
19
19
  throw new Error("Missing pin list");
20
20
  const draft = await factory.modifyTags(pins, removeEventTag(note.id));
21
- await publish("Pin note", await factory.sign(draft));
21
+ yield await factory.sign(draft);
22
22
  };
23
23
  }
24
24
  /** An action that creates a new pin list for a user */
25
25
  export function CreatePinList(pins = []) {
26
- return async ({ events, factory, self, publish }) => {
26
+ return async function* ({ events, factory, self }) {
27
27
  const existing = events.getReplaceable(kinds.Pinlist, self);
28
28
  if (existing)
29
29
  throw new Error("Pin list already exists");
30
30
  const draft = await factory.process({ kind: kinds.Pinlist }, modifyPublicTags(...pins.map((event) => addEventTag(event.id))));
31
- await publish("Create pin list", await factory.sign(draft));
31
+ yield await factory.sign(draft);
32
32
  };
33
33
  }
@@ -2,21 +2,21 @@ import { kinds } from "nostr-tools";
2
2
  import { setProfileContent, updateProfileContent } from "applesauce-factory/operations/event";
3
3
  /** An action that creates a new kind 0 profile event for a user */
4
4
  export function CreateProfile(content) {
5
- return async ({ events, factory, self, publish }) => {
5
+ return async function* ({ events, factory, self }) {
6
6
  const metadata = events.getReplaceable(kinds.Metadata, self);
7
7
  if (metadata)
8
8
  throw new Error("Profile already exists");
9
- const draft = await factory.process({ kind: kinds.Metadata }, setProfileContent(content));
10
- await publish("Create profile", await factory.sign(draft));
9
+ const draft = await factory.build({ kind: kinds.Metadata }, setProfileContent(content));
10
+ yield await factory.sign(draft);
11
11
  };
12
12
  }
13
13
  /** An action that updates a kind 0 profile evnet for a user */
14
14
  export function UpdateProfile(content) {
15
- return async ({ events, factory, self, publish }) => {
15
+ return async function* ({ events, factory, self }) {
16
16
  const metadata = events.getReplaceable(kinds.Metadata, self);
17
17
  if (!metadata)
18
18
  throw new Error("Profile does not exists");
19
19
  const draft = await factory.modify(metadata, updateProfileContent(content));
20
- await publish("Update profile", await factory.sign(draft));
20
+ yield await factory.sign(draft);
21
21
  };
22
22
  }
@@ -0,0 +1,3 @@
1
+ import { Observable } from "rxjs";
2
+ /** Subscribes to an observable, send all the values to a method and unsubscribes when complete */
3
+ export declare function play<T extends unknown = unknown>(stream: Observable<T>, method: (value: T) => void): Promise<void>;
@@ -0,0 +1,20 @@
1
+ /** Subscribes to an observable, send all the values to a method and unsubscribes when complete */
2
+ export function play(stream, method) {
3
+ return new Promise((resolve, reject) => {
4
+ const sub = stream.subscribe({
5
+ next: (v) => {
6
+ try {
7
+ method(v);
8
+ }
9
+ catch (error) {
10
+ reject(error);
11
+ }
12
+ },
13
+ error: (error) => reject(error),
14
+ complete: () => {
15
+ sub.unsubscribe();
16
+ resolve();
17
+ },
18
+ });
19
+ });
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-actions",
3
- "version": "0.0.0-next-20250313155042",
3
+ "version": "0.0.0-next-20250314133024",
4
4
  "description": "A package for performing common nostr actions",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -32,13 +32,15 @@
32
32
  }
33
33
  },
34
34
  "dependencies": {
35
- "applesauce-core": "0.0.0-next-20250313155042",
36
- "applesauce-factory": "0.0.0-next-20250313155042",
37
- "nostr-tools": "^2.10.4"
35
+ "applesauce-core": "0.0.0-next-20250314133024",
36
+ "applesauce-factory": "0.0.0-next-20250314133024",
37
+ "nostr-tools": "^2.10.4",
38
+ "rxjs": "^7.8.1"
38
39
  },
39
40
  "devDependencies": {
41
+ "@hirez_io/observer-spy": "^2.2.0",
40
42
  "@types/debug": "^4.1.12",
41
- "applesauce-signers": "0.0.0-next-20250313155042",
43
+ "applesauce-signers": "0.0.0-next-20250314133024",
42
44
  "nanoid": "^5.0.9",
43
45
  "typescript": "^5.7.3",
44
46
  "vitest": "^3.0.5"