@yaks/wake 0.0.0-stage → 0.2.36

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.
Files changed (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +325 -2
  3. package/_dist/cloudflare.d.ts +68 -0
  4. package/_dist/cloudflare.d.ts.map +1 -0
  5. package/_dist/comp.d.ts +59 -0
  6. package/_dist/comp.d.ts.map +1 -0
  7. package/_dist/deno.d.ts +40 -0
  8. package/_dist/deno.d.ts.map +1 -0
  9. package/_dist/due.d.ts +96 -0
  10. package/_dist/due.d.ts.map +1 -0
  11. package/_dist/every.d.ts +65 -0
  12. package/_dist/every.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +4 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/held.d.ts +9 -0
  16. package/_dist/held.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +59 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/plugin.d.ts +20 -0
  20. package/_dist/plugin.d.ts.map +1 -0
  21. package/_dist/run.d.ts +24 -0
  22. package/_dist/run.d.ts.map +1 -0
  23. package/_dist/service.d.ts +9 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/_dist/tick.d.ts +36 -0
  26. package/_dist/tick.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +6 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/_dist/watch.d.ts +58 -0
  32. package/_dist/watch.d.ts.map +1 -0
  33. package/_dist/while.d.ts +43 -0
  34. package/_dist/while.d.ts.map +1 -0
  35. package/cloudflare.js +80 -0
  36. package/cloudflare.js.map +1 -0
  37. package/cloudflare.ts +113 -0
  38. package/comp.js +59 -0
  39. package/comp.js.map +1 -0
  40. package/comp.ts +139 -0
  41. package/deno.js +57 -0
  42. package/deno.js.map +1 -0
  43. package/deno.json +1 -0
  44. package/deno.ts +78 -0
  45. package/due.js +147 -0
  46. package/due.js.map +1 -0
  47. package/due.ts +180 -0
  48. package/every.js +203 -0
  49. package/every.js.map +1 -0
  50. package/every.ts +223 -0
  51. package/graph.js +10 -0
  52. package/graph.js.map +1 -0
  53. package/graph.ts +11 -0
  54. package/held.js +29 -0
  55. package/held.js.map +1 -0
  56. package/held.ts +42 -0
  57. package/mod.js +59 -0
  58. package/mod.js.map +1 -0
  59. package/mod.ts +60 -0
  60. package/package.json +49 -4
  61. package/plugin.js +87 -0
  62. package/plugin.js.map +1 -0
  63. package/plugin.ts +94 -0
  64. package/run.js +124 -0
  65. package/run.js.map +1 -0
  66. package/run.ts +117 -0
  67. package/service.js +28 -0
  68. package/service.js.map +1 -0
  69. package/service.ts +42 -0
  70. package/tick.js +168 -0
  71. package/tick.js.map +1 -0
  72. package/tick.ts +181 -0
  73. package/tools.js +83 -0
  74. package/tools.js.map +1 -0
  75. package/tools.ts +76 -0
  76. package/vocab.js +14 -0
  77. package/vocab.js.map +1 -0
  78. package/vocab.json +270 -0
  79. package/vocab.ts +16 -0
  80. package/watch.js +175 -0
  81. package/watch.js.map +1 -0
  82. package/watch.ts +193 -0
  83. package/while.js +159 -0
  84. package/while.js.map +1 -0
  85. package/while.ts +176 -0
package/service.js ADDED
@@ -0,0 +1,28 @@
1
+ // The clock: the module a server imports at `@yaks/wake/service` to run this
2
+ // package's background loop for as long as the server is up. Without it the
3
+ // graph still knows perfectly well what is due and nothing ever asks — the
4
+ // wakes sit there, and no process writes `fired`.
5
+ //
6
+ // It is a long-running loop rather than an effect because nothing is committed
7
+ // when an instant arrives. A wake becomes due through the passage of time,
8
+ // which no write reports, so only running code can notice.
9
+ //
10
+ // `loop` (./deno.ts) sleeps until the next due instant rather than polling at a
11
+ // fixed rate, so an idle graph costs one timer, and a wake written a second
12
+ // from now is not made to wait out the cap.
13
+ import { loop } from "./deno.js";
14
+ /** Fire what is due, for as long as the server is up. */ export let service = (host, options = {}, signal)=>loop(host.graph, {
15
+ signal,
16
+ ...options.cap ? {
17
+ cap: options.cap
18
+ } : {},
19
+ // A wake whose own transaction was rejected is the one thing here worth
20
+ // logging: it stays due, so a server that never reports it loops in
21
+ // silence.
22
+ onTick: ({ refused })=>{
23
+ for (let { wake, error } of refused){
24
+ console.error('wake refused —', wake.entity?.eid, error);
25
+ }
26
+ }
27
+ });
28
+ //# sourceMappingURL=service.js.map
package/service.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sources":["./service.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4EAA4E;AAC5E,2EAA2E;AAC3E,kDAAkD;AAClD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,2DAA2D;AAC3D,EAAE;AACF,gFAAgF;AAChF,4EAA4E;AAC5E,4CAA4C;AAG5C,SAAS,IAAI,oBAAmB;AAUhC,uDAAuD,GACvD,OAAO,IAAI,UAAU,CACnB,MACA,UAAmB,CAAC,CAAC,EACrB,SAEA,KAAK,KAAK,KAAK,EAAE;IACf;IACA,GAAG,QAAQ,GAAG,GAAG;MAAE,KAAK,QAAQ,GAAG;IAAC,IAAI,CAAC,CAAC;IAC1C,wEAAwE;IACxE,oEAAoE;IACpE,WAAW;IACX,QAAQ,CAAC,EAAE,OAAO,EAAU;MAC1B,KAAK,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,QAAS;QACnC,QAAQ,KAAK,CAAC,kBAAkB,KAAK,MAAM,EAAE,KAAK;MACpD;IACF;EACF,GAAE"}
package/service.ts ADDED
@@ -0,0 +1,42 @@
1
+ // The clock: the module a server imports at `@yaks/wake/service` to run this
2
+ // package's background loop for as long as the server is up. Without it the
3
+ // graph still knows perfectly well what is due and nothing ever asks — the
4
+ // wakes sit there, and no process writes `fired`.
5
+ //
6
+ // It is a long-running loop rather than an effect because nothing is committed
7
+ // when an instant arrives. A wake becomes due through the passage of time,
8
+ // which no write reports, so only running code can notice.
9
+ //
10
+ // `loop` (./deno.ts) sleeps until the next due instant rather than polling at a
11
+ // fixed rate, so an idle graph costs one timer, and a wake written a second
12
+ // from now is not made to wait out the cap.
13
+
14
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
15
+ import { loop } from './deno.js'
16
+ import type { Ticked } from './tick.ts'
17
+
18
+ /** What a config file can set for this plugin. */
19
+ export type Options = {
20
+ /** the longest this may sleep, in milliseconds (default one minute) — also
21
+ * how soon a wake whose transaction was rejected is retried */
22
+ cap?: number
23
+ }
24
+
25
+ /** Fire what is due, for as long as the server is up. */
26
+ export let service = (
27
+ host: { graph: Graph },
28
+ options: Options = {},
29
+ signal?: AbortSignal,
30
+ ): Promise<void> =>
31
+ loop(host.graph, {
32
+ signal,
33
+ ...options.cap ? { cap: options.cap } : {},
34
+ // A wake whose own transaction was rejected is the one thing here worth
35
+ // logging: it stays due, so a server that never reports it loops in
36
+ // silence.
37
+ onTick: ({ refused }: Ticked) => {
38
+ for (let { wake, error } of refused) {
39
+ console.error('wake refused —', wake.entity?.eid, error)
40
+ }
41
+ },
42
+ })
package/tick.js ADDED
@@ -0,0 +1,168 @@
1
+ // Firing a wake is a write on the wake's own entity. The graph's rules decide
2
+ // what follows it, so no registry of handlers is needed and a schedule names no
3
+ // code. Each wake is written in its own transaction: one rejection leaves that
4
+ // occurrence due without rolling back the others. The precondition makes two
5
+ // processes reading the same occurrence compete at the graph's transaction
6
+ // boundary instead of both firing it, and the one that loses reads the wake
7
+ // again rather than calling the other's write a failure.
8
+ import { line, sub, whole } from "@yaks/query";
9
+ import { Stale } from "@yaks/graph/errors";
10
+ import { token } from "@yaks/graph/sha256";
11
+ import { statusOf } from "@yaks/tools/errors";
12
+ import { WAKE } from "./comp.js";
13
+ import { due, next, owed, ring, wakeOf } from "./due.js";
14
+ import { cadence, matches } from "./while.js";
15
+ import { look, watchOf } from "./watch.js";
16
+ // How many times a wake another writer keeps moving is read before it is
17
+ // left due and refused.
18
+ let TRIES = 3;
19
+ // A look its reader refused for the query's own sake (an app that is gone, a
20
+ // reader with no right to it: 400 to 404) is refused again however often it
21
+ // is asked, so it is answered as a look: the wake fires once, saying why, and
22
+ // keeps the reason (`watch.refused`), so each later look refused for it moves
23
+ // on without firing, however often a commit stirs it. A race, a pace or an
24
+ // outage (409, 429, 5xx) leaves it due, to be read again.
25
+ let answered = async (read)=>{
26
+ try {
27
+ return {
28
+ rows: await read()
29
+ };
30
+ } catch (error) {
31
+ let status = statusOf(error);
32
+ if (status < 400 || status > 404) throw error;
33
+ return {
34
+ refused: `The watched query was refused: ${error.message}`
35
+ };
36
+ }
37
+ };
38
+ /**
39
+ * Fire the due wakes, one transaction per wake, each with a precondition on
40
+ * what it read. A wake that watches a query (`watch`) is read again first and
41
+ * fires only when its rows changed, with `watch.changes` saying how; a look
42
+ * that finds nothing new moves `at` on without firing. A look the reader
43
+ * refuses for the query's own sake fires once, `watch.changes` saying why,
44
+ * and not again while later looks are refused for the same reason. `now` is
45
+ * in epoch milliseconds and becomes both `fired.at` and
46
+ * the graph's `#Now` resource. Missed occurrences collapse into one firing, and
47
+ * the recurrence advances past now — at the cadence of the first `while`
48
+ * condition that holds at `now`, else its own `every`, else not at all.
49
+ *
50
+ * ```ts
51
+ * import { tick } from '@yaks/wake'
52
+ *
53
+ * // let { fired, refused } = await tick(graph, Date.now())
54
+ * ```
55
+ */ export let tick = async (graph, now = Date.now(), opts = {})=>{
56
+ let watching = opts.watching ?? ((_, w)=>graph.read(whole(w.query)));
57
+ let result = {
58
+ fired: [],
59
+ refused: []
60
+ };
61
+ let at = new Date(now).toISOString();
62
+ let holds = matches(graph, now);
63
+ let chosen = [];
64
+ for (let wake of (await due(graph, now))){
65
+ try {
66
+ let w = wakeOf(wake) ?? {};
67
+ let every = await cadence(graph, w, now, holds) ?? w.every;
68
+ chosen.push({
69
+ wake,
70
+ every
71
+ });
72
+ } catch (error) {
73
+ chosen.push({
74
+ wake,
75
+ error
76
+ });
77
+ }
78
+ }
79
+ // A wake another writer moved since it was read is read again: still due,
80
+ // it fires from what it holds now; no longer due, that writer's instant
81
+ // stands. Only a wake that keeps moving under every read is refused.
82
+ let fire = async (wake, every)=>{
83
+ for(let tries = 1;; tries++){
84
+ try {
85
+ return await once(wake, every);
86
+ } catch (error) {
87
+ if (!(error instanceof Stale) || tries == TRIES) throw error;
88
+ }
89
+ let [fresh] = await graph.read(line`.entity.eid=${wake.entity.eid}&${sub(owed)}`, {
90
+ now
91
+ });
92
+ if (!fresh) return [];
93
+ wake = fresh;
94
+ every = await cadence(graph, wakeOf(wake) ?? {}, now, holds) ?? wakeOf(wake)?.every;
95
+ }
96
+ };
97
+ let once = async (wake, every)=>{
98
+ let w = wakeOf(wake) ?? {};
99
+ let watch = watchOf(wake);
100
+ let read = watch && await answered(()=>watching(wake, watch));
101
+ let was = watch?.refused ?? null;
102
+ let looked = read && ('refused' in read ? {
103
+ seen: watch?.seen ?? {},
104
+ changes: read.refused == was ? '' : read.refused,
105
+ refused: read.refused
106
+ } : {
107
+ ...await look(watch?.seen ?? {}, read.rows),
108
+ refused: null
109
+ });
110
+ let firing = looked && !looked.changes ? {
111
+ entity: wake.entity,
112
+ [WAKE]: {
113
+ at: next({
114
+ ...w,
115
+ every
116
+ }, now)
117
+ },
118
+ ...looked.refused != was ? {
119
+ watch: {
120
+ refused: looked.refused
121
+ }
122
+ } : {}
123
+ } : {
124
+ ...ring(wake, now, {}, every),
125
+ ...looked ? {
126
+ watch: looked
127
+ } : {}
128
+ };
129
+ let records = looked && !looked.changes ? [] : opts.records?.(wake, at, looked ? looked.changes : undefined, !!read && 'refused' in read) ?? [];
130
+ let applied = await graph.apply([
131
+ {
132
+ ...firing,
133
+ $was: {
134
+ wake: {
135
+ at: token(w.at),
136
+ every: token(w.every),
137
+ while: token(w.while)
138
+ }
139
+ }
140
+ },
141
+ ...records
142
+ ], {
143
+ now: at
144
+ });
145
+ if (looked && !looked.changes) return [];
146
+ return applied.filter((b)=>b.entity.eid == wake.entity.eid);
147
+ };
148
+ for (let choice of chosen){
149
+ let { wake } = choice;
150
+ if ('error' in choice) {
151
+ result.refused.push({
152
+ wake,
153
+ error: choice.error
154
+ });
155
+ continue;
156
+ }
157
+ try {
158
+ result.fired.push(...await fire(wake, choice.every));
159
+ } catch (error) {
160
+ result.refused.push({
161
+ wake,
162
+ error
163
+ });
164
+ }
165
+ }
166
+ return result;
167
+ };
168
+ //# sourceMappingURL=tick.js.map
package/tick.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tick.js","sources":["./tick.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,yDAAyD;AAGzD,SAAS,IAAI,EAAE,GAAG,EAAE,KAAK,2BAAgC;AACzD,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,kCAAuC;AACrD,SAAS,QAAQ,kCAAuC;AACxD,SAAS,IAAI,oBAAmB;AAChC,SAAS,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,mBAAkB;AACxD,SAAS,OAAO,EAAE,OAAO,qBAAoB;AAC7C,SAAS,IAAI,EAAiB,OAAO,qBAAoB;AAMzD,yEAAyE;AACzE,wBAAwB;AACxB,IAAI,QAAQ;AAEZ,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,0DAA0D;AAC1D,IAAI,WAAW,OAAO;EACpB,IAAI;IACF,OAAO;MAAE,MAAM,MAAM;IAAO;EAC9B,EAAE,OAAO,OAAO;IACd,IAAI,SAAS,SAAS;IACtB,IAAI,SAAS,OAAO,SAAS,KAAK,MAAM;IACxC,OAAO;MACL,SAAS,CAAC,+BAA+B,EAAE,AAAC,MAAgB,OAAO,EAAE;IACvE;EACF;AACF;AAyBA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,IAAI,OAAO,OAChB,OACA,MAAc,KAAK,GAAG,EAAE,EACxB,OAAiB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M,CAAC,GAAG;EAC9D;EACA,KAAK,IAAI,UAAU,OAAQ;IACzB,IAAI,EAAE,IAAI,EAAE,GAAG;IACf,IAAI,WAAW,QAAQ;MACrB,OAAO,OAAO,CAAC,IAAI,CAAC;QAAE;QAAM,OAAO,OAAO,KAAK;MAAC;MAChD;IACF;IACA,IAAI;MACF,OAAO,KAAK,CAAC,IAAI,IAAI,MAAM,KAAK,MAAM,OAAO,KAAK;IACpD,EAAE,OAAO,OAAO;MACd,OAAO,OAAO,CAAC,IAAI,CAAC;QAAE;QAAM;MAAM;IACpC;EACF;EACA,OAAO;AACT,EAAC"}
package/tick.ts ADDED
@@ -0,0 +1,181 @@
1
+ // Firing a wake is a write on the wake's own entity. The graph's rules decide
2
+ // what follows it, so no registry of handlers is needed and a schedule names no
3
+ // code. Each wake is written in its own transaction: one rejection leaves that
4
+ // occurrence due without rolling back the others. The precondition makes two
5
+ // processes reading the same occurrence compete at the graph's transaction
6
+ // boundary instead of both firing it, and the one that loses reads the wake
7
+ // again rather than calling the other's write a failure.
8
+
9
+ import type { Bundle, Graph } from 'jsr:@yaks/graph@0.2.36'
10
+ import { line, sub, whole } from '@yaks/query'
11
+ import { Stale } from '@yaks/graph/errors'
12
+ import { token } from '@yaks/graph/sha256'
13
+ import { statusOf } from '@yaks/tools/errors'
14
+ import { WAKE } from './comp.js'
15
+ import { due, next, owed, ring, wakeOf } from './due.js'
16
+ import { cadence, matches } from './while.js'
17
+ import { look, type Watching, watchOf } from './watch.js'
18
+
19
+ /** The part of the graph API a driver needs, also satisfied by a client for a
20
+ * remote graph over HTTP. */
21
+ export type Driver = Pick<Graph, 'read' | 'apply'>
22
+
23
+ // How many times a wake another writer keeps moving is read before it is
24
+ // left due and refused.
25
+ let TRIES = 3
26
+
27
+ // A look its reader refused for the query's own sake (an app that is gone, a
28
+ // reader with no right to it: 400 to 404) is refused again however often it
29
+ // is asked, so it is answered as a look: the wake fires once, saying why, and
30
+ // keeps the reason (`watch.refused`), so each later look refused for it moves
31
+ // on without firing, however often a commit stirs it. A race, a pace or an
32
+ // outage (409, 429, 5xx) leaves it due, to be read again.
33
+ let answered = async (read: () => Bundle[] | Promise<Bundle[]>) => {
34
+ try {
35
+ return { rows: await read() }
36
+ } catch (error) {
37
+ let status = statusOf(error)
38
+ if (status < 400 || status > 404) throw error
39
+ return {
40
+ refused: `The watched query was refused: ${(error as Error).message}`,
41
+ }
42
+ }
43
+ }
44
+
45
+ /** A committed firing and a rejected attempt are separate outcomes. Effect
46
+ * failures are reported through the graph's error reporter instead: their
47
+ * writes have already committed. */
48
+ export type Ticked = {
49
+ /** the applied wake bundles, including what the graph's rules produced */
50
+ fired: Bundle[]
51
+ /** the wakes left due, with the reason each transaction was rejected */
52
+ refused: { wake: Bundle; error: unknown }[]
53
+ }
54
+
55
+ /** How `tick` reads what a wake watches (./watch.ts). */
56
+ export type TickOpts = {
57
+ /** the rows a watched query answers for a wake; the graph's by default */
58
+ watching?: Watching
59
+ /** Records made in the same transaction as a firing. */
60
+ records?: (
61
+ wake: Bundle,
62
+ at: string,
63
+ changes?: string,
64
+ refused?: boolean,
65
+ ) => Bundle[]
66
+ }
67
+
68
+ /**
69
+ * Fire the due wakes, one transaction per wake, each with a precondition on
70
+ * what it read. A wake that watches a query (`watch`) is read again first and
71
+ * fires only when its rows changed, with `watch.changes` saying how; a look
72
+ * that finds nothing new moves `at` on without firing. A look the reader
73
+ * refuses for the query's own sake fires once, `watch.changes` saying why,
74
+ * and not again while later looks are refused for the same reason. `now` is
75
+ * in epoch milliseconds and becomes both `fired.at` and
76
+ * the graph's `#Now` resource. Missed occurrences collapse into one firing, and
77
+ * the recurrence advances past now — at the cadence of the first `while`
78
+ * condition that holds at `now`, else its own `every`, else not at all.
79
+ *
80
+ * ```ts
81
+ * import { tick } from '@yaks/wake'
82
+ *
83
+ * // let { fired, refused } = await tick(graph, Date.now())
84
+ * ```
85
+ */
86
+ export let tick = async (
87
+ graph: Driver,
88
+ now: number = Date.now(),
89
+ opts: TickOpts = {},
90
+ ): Promise<Ticked> => {
91
+ let watching = opts.watching ??
92
+ ((_: Bundle, w: { query: string }) => graph.read(whole(w.query)))
93
+ let result: Ticked = { fired: [], refused: [] }
94
+ let at = new Date(now).toISOString()
95
+ let holds = matches(graph, now)
96
+ let chosen: (
97
+ | { wake: Bundle; every: string | null | undefined }
98
+ | { wake: Bundle; error: unknown }
99
+ )[] = []
100
+ for (let wake of await due(graph, now)) {
101
+ try {
102
+ let w = wakeOf(wake) ?? {}
103
+ let every = (await cadence(graph, w, now, holds)) ?? w.every
104
+ chosen.push({ wake, every })
105
+ } catch (error) {
106
+ chosen.push({ wake, error })
107
+ }
108
+ }
109
+ // A wake another writer moved since it was read is read again: still due,
110
+ // it fires from what it holds now; no longer due, that writer's instant
111
+ // stands. Only a wake that keeps moving under every read is refused.
112
+ let fire = async (wake: Bundle, every: string | null | undefined) => {
113
+ for (let tries = 1;; tries++) {
114
+ try {
115
+ return await once(wake, every)
116
+ } catch (error) {
117
+ if (!(error instanceof Stale) || tries == TRIES) throw error
118
+ }
119
+ let [fresh] = await graph.read(
120
+ line`.entity.eid=${wake.entity.eid}&${sub(owed)}`,
121
+ { now },
122
+ )
123
+ if (!fresh) return []
124
+ wake = fresh
125
+ every = (await cadence(graph, wakeOf(wake) ?? {}, now, holds)) ??
126
+ wakeOf(wake)?.every
127
+ }
128
+ }
129
+ let once = async (wake: Bundle, every: string | null | undefined) => {
130
+ let w = wakeOf(wake) ?? {}
131
+ let watch = watchOf(wake)
132
+ let read = watch && await answered(() => watching(wake, watch))
133
+ let was = watch?.refused ?? null
134
+ let looked = read &&
135
+ ('refused' in read
136
+ ? {
137
+ seen: watch?.seen ?? {},
138
+ changes: read.refused == was ? '' : read.refused,
139
+ refused: read.refused,
140
+ }
141
+ : { ...await look(watch?.seen ?? {}, read.rows), refused: null })
142
+ let firing = looked && !looked.changes
143
+ ? {
144
+ entity: wake.entity,
145
+ [WAKE]: { at: next({ ...w, every }, now) },
146
+ ...looked.refused != was ? { watch: { refused: looked.refused } } : {},
147
+ }
148
+ : { ...ring(wake, now, {}, every), ...looked ? { watch: looked } : {} }
149
+ let records = looked && !looked.changes ? [] : opts.records?.(
150
+ wake,
151
+ at,
152
+ looked ? looked.changes : undefined,
153
+ !!read && 'refused' in read,
154
+ ) ?? []
155
+ let applied = await graph.apply([{
156
+ ...firing,
157
+ $was: {
158
+ wake: {
159
+ at: token(w.at),
160
+ every: token(w.every),
161
+ while: token(w.while),
162
+ },
163
+ },
164
+ }, ...records], { now: at })
165
+ if (looked && !looked.changes) return []
166
+ return applied.filter((b) => b.entity.eid == wake.entity.eid)
167
+ }
168
+ for (let choice of chosen) {
169
+ let { wake } = choice
170
+ if ('error' in choice) {
171
+ result.refused.push({ wake, error: choice.error })
172
+ continue
173
+ }
174
+ try {
175
+ result.fired.push(...await fire(wake, choice.every))
176
+ } catch (error) {
177
+ result.refused.push({ wake, error })
178
+ }
179
+ }
180
+ return result
181
+ }
package/tools.js ADDED
@@ -0,0 +1,83 @@
1
+ // What anybody may ask of the wakes: the `@yaks/wake/tools` entry point, the
2
+ // implementation behind the `tool: true` declarations in ./vocab.json.
3
+ // `wake_new` writes one wake aimed at something: once, at an instant, after a
4
+ // delay, or on a cadence, set for its caller. What follows a firing is the
5
+ // graph's rules', as for any wake: @yaks/session knocks a persona's operator,
6
+ // or the session opened on a topic. `wake_list` and `wake_cancel` are the
7
+ // caller's own wakes (./held.ts).
8
+ import { argsOf } from "@yaks/graph/call";
9
+ import { Refused } from "@yaks/graph/errors";
10
+ import { actorOf } from "@yaks/graph/provenance";
11
+ import { WAKE } from "./comp.js";
12
+ import { recur, when } from "./every.js";
13
+ import { cancel, held } from "./held.js";
14
+ let said = (v)=>v == null ? '' : String(v).trim();
15
+ let personOf = async (g, by)=>by && g.vocab.comp('person') && (await g.get([
16
+ by
17
+ ], [
18
+ 'person'
19
+ ]))[0]?.person ? by : undefined;
20
+ /** The implementations of `wake_new`, `wake_list` and `wake_cancel`. A
21
+ * factory, like every such module: `now` is the clock a delay counts from. */ export let runs = (o = {})=>({
22
+ wake_new: async (call, graph)=>{
23
+ let args = argsOf(call);
24
+ let every = said(args.every), at = said(args.at), note = said(args.note);
25
+ let now = (o.now ?? Date.now)();
26
+ let first = at ? when(at, now) : null;
27
+ // Set for its caller where the caller is a person the graph knows.
28
+ let by = await personOf(graph, actorOf([
29
+ call
30
+ ]).by);
31
+ if (!every && !at) {
32
+ throw new Refused('a wake needs a time: at for once, every to recur');
33
+ }
34
+ if (every && recur(every, now, now) == null) {
35
+ throw new Refused(`${every} is no cadence: a duration (30m, 1d), five cron fields ` + '(0 9 * * 1-5 America/Detroit) or @daily');
36
+ }
37
+ if (at && first == null) {
38
+ throw new Refused(`${at} is no instant: write it as 2026-01-02T09:00Z, or a delay as 10m`);
39
+ }
40
+ // The graph mints its id, and with a cadence alone gives it its first
41
+ // instant (./plugin.ts `starting`).
42
+ return [
43
+ {
44
+ entity: {
45
+ eid: '$wake'
46
+ },
47
+ [WAKE]: {
48
+ target: said(args.target),
49
+ ...every ? {
50
+ every
51
+ } : {},
52
+ ...first != null ? {
53
+ at: new Date(first).toISOString()
54
+ } : {},
55
+ ...note ? {
56
+ note
57
+ } : {},
58
+ ...by ? {
59
+ for: by
60
+ } : {}
61
+ }
62
+ }
63
+ ];
64
+ },
65
+ wake_list: async (call, graph)=>{
66
+ let by = actorOf([
67
+ call
68
+ ]).by;
69
+ return by ? await held(graph, by) : [];
70
+ },
71
+ wake_cancel: async (call, graph)=>{
72
+ let id = said(argsOf(call).wake);
73
+ let by = actorOf([
74
+ call
75
+ ]).by;
76
+ let gone = by && await cancel(graph, by, id);
77
+ if (!gone) throw new Refused(`there is no wake ${id} of yours to cancel`);
78
+ return [
79
+ gone
80
+ ];
81
+ }
82
+ });
83
+ //# sourceMappingURL=tools.js.map
package/tools.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sources":["./tools.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,uE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QAAQ;YAAE,KAAK;UAAQ;UACvB,CAAC,KAAK,EAAE;YACN,QAAQ,KAAK,KAAK,MAAM;YACxB,GAAG,QAAQ;cAAE;YAAM,IAAI,CAAC,CAAC;YACzB,GAAG,SAAS,OAAO;cAAE,IAAI,IAAI,KAAK,OAAO,WAAW;YAAG,IAAI,CAAC,CAAC;YAC7D,GAAG,OAAO;cAAE;YAAK,IAAI,CAAC,CAAC;YACvB,GAAG,KAAK;cAAE,KAAK;YAAG,IAAI,CAAC,CAAC;UAC1B;QACF;OAAE;IACJ;IACA,WAAW,OAAO,MAAM;MACtB,IAAI,KAAK,QAAQ;QAAC;OAAK,EAAE,EAAE;MAC3B,OAAO,KAAK,MAAM,KAAK,OAAO,MAAM,EAAE;IACxC;IACA,aAAa,OAAO,MAAM;MACxB,IAAI,KAAK,KAAK,OAAO,MAAM,IAAI;MAC/B,IAAI,KAAK,QAAQ;QAAC;OAAK,EAAE,EAAE;MAC3B,IAAI,OAAO,MAAM,MAAM,OAAO,OAAO,IAAI;MACzC,IAAI,CAAC,MAAM,MAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,GAAG,mBAAmB,CAAC;MACxE,OAAO;QAAC;OAAK;IACf;EACF,CAAC,EAAC"}
package/tools.ts ADDED
@@ -0,0 +1,76 @@
1
+ // What anybody may ask of the wakes: the `@yaks/wake/tools` entry point, the
2
+ // implementation behind the `tool: true` declarations in ./vocab.json.
3
+ // `wake_new` writes one wake aimed at something: once, at an instant, after a
4
+ // delay, or on a cadence, set for its caller. What follows a firing is the
5
+ // graph's rules', as for any wake: @yaks/session knocks a persona's operator,
6
+ // or the session opened on a topic. `wake_list` and `wake_cancel` are the
7
+ // caller's own wakes (./held.ts).
8
+
9
+ import type { Bundle, Graph } from 'jsr:@yaks/graph@0.2.36'
10
+ import { argsOf } from '@yaks/graph/call'
11
+ import { Refused } from '@yaks/graph/errors'
12
+ import { actorOf } from '@yaks/graph/provenance'
13
+ import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
14
+ import { WAKE } from './comp.js'
15
+ import { recur, when } from './every.js'
16
+ import { cancel, held } from './held.js'
17
+
18
+ let said = (v: unknown): string => v == null ? '' : String(v).trim()
19
+
20
+ let personOf = async (
21
+ g: Pick<Graph, 'get' | 'vocab'>,
22
+ by?: string,
23
+ ): Promise<string | undefined> =>
24
+ by && g.vocab.comp('person') && (await g.get([by], ['person']))[0]?.person
25
+ ? by
26
+ : undefined
27
+
28
+ /** The implementations of `wake_new`, `wake_list` and `wake_cancel`. A
29
+ * factory, like every such module: `now` is the clock a delay counts from. */
30
+ export let runs = (o: { now?: () => number } = {}): Runs => ({
31
+ wake_new: async (call, graph): Promise<Bundle[]> => {
32
+ let args = argsOf(call)
33
+ let every = said(args.every), at = said(args.at), note = said(args.note)
34
+ let now = (o.now ?? Date.now)()
35
+ let first = at ? when(at, now) : null
36
+ // Set for its caller where the caller is a person the graph knows.
37
+ let by = await personOf(graph, actorOf([call]).by)
38
+ if (!every && !at) {
39
+ throw new Refused('a wake needs a time: at for once, every to recur')
40
+ }
41
+ if (every && recur(every, now, now) == null) {
42
+ throw new Refused(
43
+ `${every} is no cadence: a duration (30m, 1d), five cron fields ` +
44
+ '(0 9 * * 1-5 America/Detroit) or @daily',
45
+ )
46
+ }
47
+ if (at && first == null) {
48
+ throw new Refused(
49
+ `${at} is no instant: write it as 2026-01-02T09:00Z, or a delay as 10m`,
50
+ )
51
+ }
52
+ // The graph mints its id, and with a cadence alone gives it its first
53
+ // instant (./plugin.ts `starting`).
54
+ return [{
55
+ entity: { eid: '$wake' },
56
+ [WAKE]: {
57
+ target: said(args.target),
58
+ ...every ? { every } : {},
59
+ ...first != null ? { at: new Date(first).toISOString() } : {},
60
+ ...note ? { note } : {},
61
+ ...by ? { for: by } : {},
62
+ },
63
+ }]
64
+ },
65
+ wake_list: async (call, graph) => {
66
+ let by = actorOf([call]).by
67
+ return by ? await held(graph, by) : []
68
+ },
69
+ wake_cancel: async (call, graph) => {
70
+ let id = said(argsOf(call).wake)
71
+ let by = actorOf([call]).by
72
+ let gone = by && await cancel(graph, by, id)
73
+ if (!gone) throw new Refused(`there is no wake ${id} of yours to cancel`)
74
+ return [gone]
75
+ },
76
+ })
package/vocab.js ADDED
@@ -0,0 +1,14 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/wake/vocab`. It reaches no storage, no SQL and
3
+ // no runtime, so a browser tab loading this vocabulary loads nothing else.
4
+ import { wakeDoc } from "./comp.js";
5
+ import manifest from './package.json' with {
6
+ type: 'json'
7
+ };
8
+ export { wakeDoc };
9
+ /** What this package is: its manifest's description, the one place it is
10
+ * written, which a host stamps on each document here. */ export let description = manifest.description;
11
+ /** Every document this plugin declares. */ export let docs = [
12
+ wakeDoc
13
+ ];
14
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,gFAAgF;AAChF,2EAA2E;AAG3E,SAAS,OAAO,oBAAmB;AACnC,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,SAAS,OAAO,GAAE;AAElB;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAQ,CAAA"}