nowity 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +751 -0
  2. package/dist/api/contract.d.ts +186 -0
  3. package/dist/api/contract.d.ts.map +1 -0
  4. package/dist/api/contract.js +251 -0
  5. package/dist/api/errors.d.ts +50 -0
  6. package/dist/api/errors.d.ts.map +1 -0
  7. package/dist/api/errors.js +50 -0
  8. package/dist/api/index.d.ts +13 -0
  9. package/dist/api/index.d.ts.map +1 -0
  10. package/dist/api/index.js +32 -0
  11. package/dist/client/confirmed-store.d.ts +33 -0
  12. package/dist/client/confirmed-store.d.ts.map +1 -0
  13. package/dist/client/confirmed-store.js +123 -0
  14. package/dist/client/connection.d.ts +102 -0
  15. package/dist/client/connection.d.ts.map +1 -0
  16. package/dist/client/connection.js +285 -0
  17. package/dist/client/list.d.ts +102 -0
  18. package/dist/client/list.d.ts.map +1 -0
  19. package/dist/client/list.js +257 -0
  20. package/dist/client/live-query.d.ts +153 -0
  21. package/dist/client/live-query.d.ts.map +1 -0
  22. package/dist/client/live-query.js +244 -0
  23. package/dist/client/nowity-client.d.ts +188 -0
  24. package/dist/client/nowity-client.d.ts.map +1 -0
  25. package/dist/client/nowity-client.js +580 -0
  26. package/dist/client/null-transport.d.ts +16 -0
  27. package/dist/client/null-transport.d.ts.map +1 -0
  28. package/dist/client/null-transport.js +17 -0
  29. package/dist/client/overlay.d.ts +44 -0
  30. package/dist/client/overlay.d.ts.map +1 -0
  31. package/dist/client/overlay.js +90 -0
  32. package/dist/client/query-source.d.ts +78 -0
  33. package/dist/client/query-source.d.ts.map +1 -0
  34. package/dist/client/query-source.js +57 -0
  35. package/dist/client/ssr-source.d.ts +70 -0
  36. package/dist/client/ssr-source.d.ts.map +1 -0
  37. package/dist/client/ssr-source.js +134 -0
  38. package/dist/client/transport.d.ts +19 -0
  39. package/dist/client/transport.d.ts.map +1 -0
  40. package/dist/client/transport.js +2 -0
  41. package/dist/client/ws-transport.d.ts +30 -0
  42. package/dist/client/ws-transport.d.ts.map +1 -0
  43. package/dist/client/ws-transport.js +89 -0
  44. package/dist/client.d.ts +47 -0
  45. package/dist/client.d.ts.map +1 -0
  46. package/dist/client.js +80 -0
  47. package/dist/core/diff.d.ts +14 -0
  48. package/dist/core/diff.d.ts.map +1 -0
  49. package/dist/core/diff.js +56 -0
  50. package/dist/core/normalize.d.ts +16 -0
  51. package/dist/core/normalize.d.ts.map +1 -0
  52. package/dist/core/normalize.js +67 -0
  53. package/dist/core/protocol.d.ts +215 -0
  54. package/dist/core/protocol.d.ts.map +1 -0
  55. package/dist/core/protocol.js +14 -0
  56. package/dist/core/ssr-bridge.d.ts +69 -0
  57. package/dist/core/ssr-bridge.d.ts.map +1 -0
  58. package/dist/core/ssr-bridge.js +40 -0
  59. package/dist/core/types.d.ts +96 -0
  60. package/dist/core/types.d.ts.map +1 -0
  61. package/dist/core/types.js +17 -0
  62. package/dist/index.d.ts +47 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +98 -0
  65. package/dist/ironbean/client.d.ts +7 -0
  66. package/dist/ironbean/client.d.ts.map +1 -0
  67. package/dist/ironbean/client.js +38 -0
  68. package/dist/ironbean/server.d.ts +42 -0
  69. package/dist/ironbean/server.d.ts.map +1 -0
  70. package/dist/ironbean/server.js +62 -0
  71. package/dist/ironbean/tokens.d.ts +26 -0
  72. package/dist/ironbean/tokens.d.ts.map +1 -0
  73. package/dist/ironbean/tokens.js +23 -0
  74. package/dist/next/config.d.ts +7 -0
  75. package/dist/next/config.d.ts.map +1 -0
  76. package/dist/next/config.js +77 -0
  77. package/dist/next/live.d.ts +69 -0
  78. package/dist/next/live.d.ts.map +1 -0
  79. package/dist/next/live.js +70 -0
  80. package/dist/next/serve.d.ts +44 -0
  81. package/dist/next/serve.d.ts.map +1 -0
  82. package/dist/next/serve.js +107 -0
  83. package/dist/next/server.d.ts +62 -0
  84. package/dist/next/server.d.ts.map +1 -0
  85. package/dist/next/server.js +127 -0
  86. package/dist/react/connection-context.d.ts +4 -0
  87. package/dist/react/connection-context.d.ts.map +1 -0
  88. package/dist/react/connection-context.js +28 -0
  89. package/dist/react/grid-list.d.ts +34 -0
  90. package/dist/react/grid-list.d.ts.map +1 -0
  91. package/dist/react/grid-list.js +62 -0
  92. package/dist/react/hydrate.d.ts +22 -0
  93. package/dist/react/hydrate.d.ts.map +1 -0
  94. package/dist/react/hydrate.js +18 -0
  95. package/dist/react/index.d.ts +35 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +51 -0
  98. package/dist/react/list.d.ts +31 -0
  99. package/dist/react/list.d.ts.map +1 -0
  100. package/dist/react/list.js +35 -0
  101. package/dist/react/prerendered.d.ts +33 -0
  102. package/dist/react/prerendered.d.ts.map +1 -0
  103. package/dist/react/prerendered.js +165 -0
  104. package/dist/react/provider.d.ts +64 -0
  105. package/dist/react/provider.d.ts.map +1 -0
  106. package/dist/react/provider.js +130 -0
  107. package/dist/react/refusals.d.ts +31 -0
  108. package/dist/react/refusals.d.ts.map +1 -0
  109. package/dist/react/refusals.js +51 -0
  110. package/dist/react/restricted.d.ts +76 -0
  111. package/dist/react/restricted.d.ts.map +1 -0
  112. package/dist/react/restricted.js +126 -0
  113. package/dist/react/use-list.d.ts +42 -0
  114. package/dist/react/use-list.d.ts.map +1 -0
  115. package/dist/react/use-list.js +56 -0
  116. package/dist/react/use-query.d.ts +66 -0
  117. package/dist/react/use-query.d.ts.map +1 -0
  118. package/dist/react/use-query.js +126 -0
  119. package/dist/react/virtual.d.ts +60 -0
  120. package/dist/react/virtual.d.ts.map +1 -0
  121. package/dist/react/virtual.js +131 -0
  122. package/dist/server/api/auth.d.ts +37 -0
  123. package/dist/server/api/auth.d.ts.map +1 -0
  124. package/dist/server/api/auth.js +54 -0
  125. package/dist/server/api/bridge.d.ts +28 -0
  126. package/dist/server/api/bridge.d.ts.map +1 -0
  127. package/dist/server/api/bridge.js +330 -0
  128. package/dist/server/api/collector.d.ts +25 -0
  129. package/dist/server/api/collector.d.ts.map +1 -0
  130. package/dist/server/api/collector.js +184 -0
  131. package/dist/server/api/configure.d.ts +31 -0
  132. package/dist/server/api/configure.d.ts.map +1 -0
  133. package/dist/server/api/configure.js +67 -0
  134. package/dist/server/api/execution.d.ts +77 -0
  135. package/dist/server/api/execution.d.ts.map +1 -0
  136. package/dist/server/api/execution.js +97 -0
  137. package/dist/server/api/list.d.ts +141 -0
  138. package/dist/server/api/list.d.ts.map +1 -0
  139. package/dist/server/api/list.js +281 -0
  140. package/dist/server/api/prerender.d.ts +32 -0
  141. package/dist/server/api/prerender.d.ts.map +1 -0
  142. package/dist/server/api/prerender.js +69 -0
  143. package/dist/server/api/read-keys.d.ts +128 -0
  144. package/dist/server/api/read-keys.d.ts.map +1 -0
  145. package/dist/server/api/read-keys.js +464 -0
  146. package/dist/server/api/read-set.d.ts +103 -0
  147. package/dist/server/api/read-set.d.ts.map +1 -0
  148. package/dist/server/api/read-set.js +210 -0
  149. package/dist/server/api/runtime.d.ts +36 -0
  150. package/dist/server/api/runtime.d.ts.map +1 -0
  151. package/dist/server/api/runtime.js +49 -0
  152. package/dist/server/api/tracked-client.d.ts +6 -0
  153. package/dist/server/api/tracked-client.d.ts.map +1 -0
  154. package/dist/server/api/tracked-client.js +56 -0
  155. package/dist/server/change-source/change-source.d.ts +41 -0
  156. package/dist/server/change-source/change-source.d.ts.map +1 -0
  157. package/dist/server/change-source/change-source.js +2 -0
  158. package/dist/server/change-source/outbox-change-source.d.ts +106 -0
  159. package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
  160. package/dist/server/change-source/outbox-change-source.js +237 -0
  161. package/dist/server/change-source/wal-change-source.d.ts +85 -0
  162. package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
  163. package/dist/server/change-source/wal-change-source.js +193 -0
  164. package/dist/server/db.d.ts +51 -0
  165. package/dist/server/db.d.ts.map +1 -0
  166. package/dist/server/db.js +53 -0
  167. package/dist/server/evaluate.d.ts +39 -0
  168. package/dist/server/evaluate.d.ts.map +1 -0
  169. package/dist/server/evaluate.js +61 -0
  170. package/dist/server/invalidation-index.d.ts +64 -0
  171. package/dist/server/invalidation-index.d.ts.map +1 -0
  172. package/dist/server/invalidation-index.js +0 -0
  173. package/dist/server/mutator.d.ts +59 -0
  174. package/dist/server/mutator.d.ts.map +1 -0
  175. package/dist/server/mutator.js +77 -0
  176. package/dist/server/query.d.ts +113 -0
  177. package/dist/server/query.d.ts.map +1 -0
  178. package/dist/server/query.js +35 -0
  179. package/dist/server/setup.d.ts +30 -0
  180. package/dist/server/setup.d.ts.map +1 -0
  181. package/dist/server/setup.js +107 -0
  182. package/dist/server/sql/setup.sql +215 -0
  183. package/dist/server/ssr.d.ts +29 -0
  184. package/dist/server/ssr.d.ts.map +1 -0
  185. package/dist/server/ssr.js +43 -0
  186. package/dist/server/sync-engine.d.ts +256 -0
  187. package/dist/server/sync-engine.d.ts.map +1 -0
  188. package/dist/server/sync-engine.js +805 -0
  189. package/dist/server/ws-server.d.ts +56 -0
  190. package/dist/server/ws-server.d.ts.map +1 -0
  191. package/dist/server/ws-server.js +241 -0
  192. package/package.json +81 -0
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.Virtual = void 0;
5
+ const jsx_runtime_1 = require("react/jsx-runtime");
6
+ /**
7
+ * The geometry both {@link GridList} and {@link List} are made of.
8
+ *
9
+ * Internal: nothing exported here reaches `nowity/client`. What a person picks
10
+ * between is a grid and a list, and the difference between those two is one
11
+ * function — how many items fit across — so that is the only thing this takes
12
+ * from either of them. Everything else, from measuring the box to deciding
13
+ * which windows stay open, is the same work said once.
14
+ */
15
+ const react_1 = require("react");
16
+ const mobx_react_lite_1 = require("mobx-react-lite");
17
+ /**
18
+ * An `observer` in its own right, and not only because its wrappers are.
19
+ *
20
+ * `observer` tracks the render it wraps, and `<List>` renders an *element* —
21
+ * everything below is a separate render as far as MobX is concerned. So the one
22
+ * observable this reads, `list.total`, has to be tracked here or a collection
23
+ * that grows would only redraw when something else in the tree happened to be
24
+ * watching it. A row appearing in a list nobody prints a count beside is exactly
25
+ * that case.
26
+ */
27
+ exports.Virtual = (0, mobx_react_lite_1.observer)(function Virtual(props) {
28
+ const { of: list, children, itemHeight, gap = 0, overscan = 2, height = 400, windowScroll = false, initialCount = 24, empty = null, className, style, columnsOf, template, } = props;
29
+ const ref = (0, react_1.useRef)(null);
30
+ const viewport = useViewport(ref, windowScroll);
31
+ const total = list.total;
32
+ const columns = columnsOf(viewport.width);
33
+ const rowHeight = itemHeight + gap;
34
+ const rowCount = Math.ceil(total / columns);
35
+ // Before the viewport is measured there is neither a scroll position to
36
+ // render around nor a width to divide, so nothing is virtualised yet: the
37
+ // opening screenful is laid out as an ordinary grid and the browser decides
38
+ // how many fit across. That is the server's answer, and the browser's first
39
+ // paint reproduces it exactly, which is what keeps hydration quiet — and it
40
+ // is a real layout rather than a one-column placeholder for one, because
41
+ // `auto-fill` needs no measurement to do what the arithmetic below does.
42
+ const measured = viewport.height > 0;
43
+ const firstRow = measured ? Math.max(0, Math.floor(viewport.top / rowHeight) - overscan) : 0;
44
+ const lastRow = measured
45
+ ? Math.min(rowCount, firstRow + Math.ceil(viewport.height / rowHeight) + overscan * 2 + 1)
46
+ : 0;
47
+ const from = measured ? firstRow * columns : 0;
48
+ const to = measured ? Math.min(total, lastRow * columns) : Math.min(total, initialCount);
49
+ // Which windows stay open. In an effect rather than in render, because it is
50
+ // the same statement about lifetime that every other subscription makes:
51
+ // held while something committed is showing it.
52
+ (0, react_1.useEffect)(() => list.view(from, to), [list, from, to]);
53
+ (0, react_1.useEffect)(() => () => list.view(0, 0), [list]);
54
+ if (total === 0) {
55
+ return ((0, jsx_runtime_1.jsx)("div", { ref: ref, className: className, style: style, children: empty }));
56
+ }
57
+ const indices = [];
58
+ for (let index = from; index < to; index += 1)
59
+ indices.push(index);
60
+ return ((0, jsx_runtime_1.jsx)("div", { ref: ref, className: className, style: {
61
+ ...(windowScroll ? {} : { height, overflowY: "auto" }),
62
+ ...style,
63
+ }, children: (0, jsx_runtime_1.jsx)("div", { style: measured ? { height: rowCount * rowHeight - gap, position: "relative" } : undefined, children: (0, jsx_runtime_1.jsx)("div", { style: {
64
+ ...(measured
65
+ ? { position: "absolute", top: firstRow * rowHeight, left: 0, right: 0 }
66
+ : null),
67
+ display: "grid",
68
+ gridTemplateColumns: template,
69
+ gap,
70
+ }, children: indices.map((index) => ((0, jsx_runtime_1.jsx)(Cell, { list: list, index: index, height: itemHeight, render: children }, index))) }) }) }));
71
+ });
72
+ /**
73
+ * One cell, observing one row.
74
+ *
75
+ * Its own `observer` and not the grid's: a row that changes must re-render the
76
+ * cell showing it and nothing else, which is the same field-level tracking the
77
+ * rest of the framework is built on — and the reason a live grid can afford to
78
+ * be live at all.
79
+ */
80
+ const Cell = (0, mobx_react_lite_1.observer)(function Cell({ list, index, height, render, }) {
81
+ return (0, jsx_runtime_1.jsx)("div", { style: { height, overflow: "hidden" }, children: render(list.at(index), index) });
82
+ });
83
+ /**
84
+ * What part of the list is on screen.
85
+ *
86
+ * Measured rather than tracked: scroll position, box size and window size all
87
+ * change independently, and a `getBoundingClientRect` on each of them is both
88
+ * simpler and more honest than keeping three numbers in step by hand.
89
+ */
90
+ function useViewport(ref, windowScroll) {
91
+ const [viewport, setViewport] = (0, react_1.useState)({ top: 0, height: 0, width: 0 });
92
+ (0, react_1.useEffect)(() => {
93
+ const element = ref.current;
94
+ if (!element)
95
+ return;
96
+ const measure = () => {
97
+ const next = windowScroll
98
+ ? {
99
+ top: Math.max(0, -element.getBoundingClientRect().top),
100
+ height: window.innerHeight,
101
+ width: element.clientWidth,
102
+ }
103
+ : {
104
+ top: element.scrollTop,
105
+ height: element.clientHeight,
106
+ width: element.clientWidth,
107
+ };
108
+ // Scroll fires far more often than the rendered range changes, and a
109
+ // new object every time would re-render the grid on every pixel.
110
+ setViewport((previous) => previous.top === next.top &&
111
+ previous.height === next.height &&
112
+ previous.width === next.width
113
+ ? previous
114
+ : next);
115
+ };
116
+ measure();
117
+ const scroller = windowScroll
118
+ ? window
119
+ : element;
120
+ scroller.addEventListener("scroll", measure, { passive: true });
121
+ window.addEventListener("resize", measure);
122
+ const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => measure());
123
+ resize?.observe(element);
124
+ return () => {
125
+ scroller.removeEventListener("scroll", measure);
126
+ window.removeEventListener("resize", measure);
127
+ resize?.disconnect();
128
+ };
129
+ }, [ref, windowScroll]);
130
+ return viewport;
131
+ }
@@ -0,0 +1,37 @@
1
+ import type { AuthRequest, AuthResult } from "../ws-server";
2
+ /**
3
+ * Who is on the other end of a connection.
4
+ *
5
+ * A component rather than a callback, so the application implements it the same
6
+ * way it implements everything else — in a class, in the container, able to take
7
+ * its own dependencies. Authentication is rarely a pure function of the request:
8
+ * it wants a session store, a token verifier, a clock.
9
+ *
10
+ * ```ts
11
+ * @component
12
+ * export class CookieAuth extends Authenticator {
13
+ * authenticate({ headers }: AuthRequest) {
14
+ * const userId = readSessionCookie(headers.cookie);
15
+ * return userId ? { userId } : null;
16
+ * }
17
+ * }
18
+ * ```
19
+ *
20
+ * The upgrade is an ordinary HTTP request on the application's own origin, so
21
+ * `headers.cookie` is the session cookie the pages already use.
22
+ *
23
+ * Returning null refuses the connection. The default refuses nothing and
24
+ * identifies nobody, which is right for a prototype and wrong for anything else.
25
+ *
26
+ * One caveat worth knowing before injecting things here: this runs *outside* a
27
+ * query or mutation, so the ambient `Db` has no execution to bind to. Inject the
28
+ * Prisma client itself if authentication needs the database.
29
+ */
30
+ export declare abstract class Authenticator {
31
+ abstract authenticate(request: AuthRequest): Promise<AuthResult | null> | AuthResult | null;
32
+ }
33
+ /** What you get when nothing is bound: anonymous, and honest about it. */
34
+ export declare class AnonymousAuthenticator extends Authenticator {
35
+ authenticate(): AuthResult;
36
+ }
37
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/server/api/auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,8BACsB,aAAa;IAC/B,QAAQ,CAAC,YAAY,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG,UAAU,GAAG,IAAI;CAC9F;AAED,0EAA0E;AAC1E,qBACa,sBAAuB,SAAQ,aAAa;IACrD,YAAY,IAAI,UAAU;CAG7B"}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.AnonymousAuthenticator = exports.Authenticator = void 0;
10
+ const ironbean_1 = require("ironbean");
11
+ /**
12
+ * Who is on the other end of a connection.
13
+ *
14
+ * A component rather than a callback, so the application implements it the same
15
+ * way it implements everything else — in a class, in the container, able to take
16
+ * its own dependencies. Authentication is rarely a pure function of the request:
17
+ * it wants a session store, a token verifier, a clock.
18
+ *
19
+ * ```ts
20
+ * @component
21
+ * export class CookieAuth extends Authenticator {
22
+ * authenticate({ headers }: AuthRequest) {
23
+ * const userId = readSessionCookie(headers.cookie);
24
+ * return userId ? { userId } : null;
25
+ * }
26
+ * }
27
+ * ```
28
+ *
29
+ * The upgrade is an ordinary HTTP request on the application's own origin, so
30
+ * `headers.cookie` is the session cookie the pages already use.
31
+ *
32
+ * Returning null refuses the connection. The default refuses nothing and
33
+ * identifies nobody, which is right for a prototype and wrong for anything else.
34
+ *
35
+ * One caveat worth knowing before injecting things here: this runs *outside* a
36
+ * query or mutation, so the ambient `Db` has no execution to bind to. Inject the
37
+ * Prisma client itself if authentication needs the database.
38
+ */
39
+ let Authenticator = class Authenticator {
40
+ };
41
+ exports.Authenticator = Authenticator;
42
+ exports.Authenticator = Authenticator = __decorate([
43
+ ironbean_1.component
44
+ ], Authenticator);
45
+ /** What you get when nothing is bound: anonymous, and honest about it. */
46
+ let AnonymousAuthenticator = class AnonymousAuthenticator extends Authenticator {
47
+ authenticate() {
48
+ return { userId: null };
49
+ }
50
+ };
51
+ exports.AnonymousAuthenticator = AnonymousAuthenticator;
52
+ exports.AnonymousAuthenticator = AnonymousAuthenticator = __decorate([
53
+ ironbean_1.component
54
+ ], AnonymousAuthenticator);
@@ -0,0 +1,28 @@
1
+ import { type ApiManifest, type ContractMeta } from "../../api/contract";
2
+ import { MutatorRegistry } from "../mutator";
3
+ import { QueryRegistry } from "../query";
4
+ import type { ReadSetTracker } from "./read-set";
5
+ /** Entity metadata the client needs, derived from the schema rather than configured. */
6
+ export interface EntityDescriptorWire {
7
+ idField?: string;
8
+ relations?: Record<string, {
9
+ entity: string;
10
+ localKey?: string;
11
+ }>;
12
+ }
13
+ export interface BuiltApi {
14
+ queries: QueryRegistry;
15
+ mutators: MutatorRegistry;
16
+ manifest: ApiManifest;
17
+ /** Entity shapes for the client identity map, keyed by entity name. */
18
+ entities: Record<string, EntityDescriptorWire>;
19
+ }
20
+ export interface BuildApiOptions {
21
+ contracts: ContractMeta[];
22
+ tracker: ReadSetTracker;
23
+ /** How to obtain the implementation instance — the DI container's `getBean`. */
24
+ resolve: (contract: Function) => any;
25
+ onWarning?: (message: string) => void;
26
+ }
27
+ export declare function buildApi(options: BuildApiOptions): BuiltApi;
28
+ //# sourceMappingURL=bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../../../src/server/api/bridge.ts"],"names":[],"mappings":"AAWA,OAAO,EAKH,KAAK,WAAW,EAChB,KAAK,YAAY,EAEpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAoB,eAAe,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAuC,MAAM,UAAU,CAAC;AAY9E,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,YAAY,CAAC;AAE/D,wFAAwF;AACxF,MAAM,WAAW,oBAAoB;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACrE;AAED,MAAM,WAAW,QAAQ;IACrB,OAAO,EAAE,aAAa,CAAC;IACvB,QAAQ,EAAE,eAAe,CAAC;IAC1B,QAAQ,EAAE,WAAW,CAAC;IACtB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC;CAClD;AAED,MAAM,WAAW,eAAe;IAC5B,SAAS,EAAE,YAAY,EAAE,CAAC;IAC1B,OAAO,EAAE,cAAc,CAAC;IACxB,gFAAgF;IAChF,OAAO,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,GAAG,CAAC;IACrC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAwG3D"}
@@ -0,0 +1,330 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildApi = buildApi;
4
+ /**
5
+ * From decorated methods to what the sync engine already understands.
6
+ *
7
+ * The engine's vocabulary — `QueryDef`, `MutatorDef` — does not change. What
8
+ * changes is where those definitions come from: instead of being written by
9
+ * hand, with their invalidation dependencies declared alongside, they are
10
+ * derived from an implementation class and fill their dependencies in from what
11
+ * each execution actually read.
12
+ */
13
+ const types_1 = require("../../core/types");
14
+ const errors_1 = require("../../api/errors");
15
+ const contract_1 = require("../../api/contract");
16
+ const mutator_1 = require("../mutator");
17
+ const query_1 = require("../query");
18
+ const execution_1 = require("./execution");
19
+ const list_1 = require("./list");
20
+ const read_keys_1 = require("./read-keys");
21
+ function buildApi(options) {
22
+ const { contracts, tracker, resolve } = options;
23
+ const warn = options.onWarning ?? ((message) => console.warn("[nowity/api]", message));
24
+ const queries = new query_1.QueryRegistry();
25
+ const mutators = new mutator_1.MutatorRegistry();
26
+ for (const contract of contracts) {
27
+ if (!contract.impl) {
28
+ throw new Error(`API contract "${contract.name}" has no implementation in this process. ` +
29
+ `Import the module that defines it before starting the server.`);
30
+ }
31
+ for (const endpoint of contract.endpoints.values()) {
32
+ const name = (0, contract_1.endpointName)(contract.name, endpoint.method);
33
+ const call = (execution, args) => {
34
+ const instance = resolve(contract.contract);
35
+ const positional = Array.isArray(args) ? args : [args];
36
+ return (0, execution_1.runInExecution)(execution, () => instance[endpoint.method](...positional));
37
+ };
38
+ if (endpoint.kind === "query") {
39
+ const queryOptions = endpoint.query ?? {};
40
+ queries.define({
41
+ name,
42
+ entity: queryOptions.entity ?? contract.name,
43
+ idField: queryOptions.idField,
44
+ tables: queryOptions.tables ?? [],
45
+ tracksReads: true,
46
+ run: async (args, ctx) => {
47
+ const execution = queryExecution(ctx, tracker);
48
+ let returned;
49
+ try {
50
+ returned = await call(execution, args);
51
+ }
52
+ catch (err) {
53
+ // A refusal still carries what it read on the way to
54
+ // saying no — that is what gets watched afterwards.
55
+ if ((0, errors_1.isForbidden)(err)) {
56
+ err.tables = readSetOf(execution, queryOptions);
57
+ err.keys = keySetOf(execution, queryOptions);
58
+ }
59
+ throw err;
60
+ }
61
+ if (execution.untracked && !queryOptions.tables?.length) {
62
+ warn(`Query "${name}" read something the tracker cannot see (raw SQL?). ` +
63
+ `It will be revalidated on every transaction until you declare ` +
64
+ `@query({ tables: [...] }).`);
65
+ }
66
+ return shape(returned, execution, queryOptions, tracker, name);
67
+ },
68
+ });
69
+ continue;
70
+ }
71
+ if (endpoint.kind === "list") {
72
+ defineListQueries({
73
+ queries,
74
+ endpoint: name,
75
+ options: endpoint.query ?? {},
76
+ fallbackEntity: contract.name,
77
+ call,
78
+ tracker,
79
+ warn,
80
+ });
81
+ continue;
82
+ }
83
+ mutators.define({
84
+ name,
85
+ server: async (args, ctx) => {
86
+ const execution = {
87
+ kind: "mutation",
88
+ session: ctx.session,
89
+ prisma: ctx.db.client,
90
+ reads: new Set(),
91
+ untracked: false,
92
+ mutationId: ctx.mutationId,
93
+ };
94
+ try {
95
+ await call(execution, args);
96
+ }
97
+ catch (err) {
98
+ // The engine already knows how to treat a refused write;
99
+ // `Rejected` is only the API layer's name for it.
100
+ if ((0, errors_1.isRejected)(err))
101
+ throw new mutator_1.MutationRejected(err.message);
102
+ throw err;
103
+ }
104
+ },
105
+ });
106
+ }
107
+ }
108
+ return {
109
+ queries,
110
+ mutators,
111
+ manifest: (0, contract_1.buildManifest)(contracts),
112
+ entities: entityDescriptors(tracker),
113
+ };
114
+ }
115
+ /**
116
+ * The largest window a client may ask for in one subscription.
117
+ *
118
+ * A page is a viewport, and no viewport is a thousand rows deep. The bound
119
+ * exists because the offset and the limit arrive from a browser, and "how many
120
+ * rows may I make the server materialise at once" is not a browser's decision.
121
+ */
122
+ const MAX_PAGE = 500;
123
+ /**
124
+ * The two live queries one `@list` endpoint is served through.
125
+ *
126
+ * A window and a total, because those are the two questions a virtualised list
127
+ * asks and they have different lifetimes: the total is read once and watched for
128
+ * as long as the list is on screen, while windows come and go with the
129
+ * scrollbar. Splitting them is what lets a browser hold three subscriptions for
130
+ * a collection of a hundred thousand rows.
131
+ *
132
+ * Both run the same method, so both carry the same permission check and the same
133
+ * read set — a membership withdrawn empties the list and zeroes its count in one
134
+ * transaction, without either of them knowing the other exists.
135
+ */
136
+ function defineListQueries(deps) {
137
+ const { queries, endpoint, options, call, tracker, warn } = deps;
138
+ const plans = new list_1.ListPlans();
139
+ /** One run of the endpoint, with the window pushed in where it fits. */
140
+ const evaluate = async (want, args, ctx) => {
141
+ let execution;
142
+ const run = async (list) => {
143
+ execution = queryExecution(ctx, tracker, list);
144
+ return { execution, returned: await call(execution, args) };
145
+ };
146
+ try {
147
+ const outcome = await (0, list_1.evaluateList)(plans, endpoint, want, run, (model, field) => tracker.fieldKind(model, field));
148
+ if (outcome.execution.untracked && !options.tables?.length) {
149
+ warn(`List "${endpoint}" read something the tracker cannot see (raw SQL?). ` +
150
+ `It will be revalidated on every transaction until you declare ` +
151
+ `@list({ tables: [...] }).`);
152
+ }
153
+ return outcome;
154
+ }
155
+ catch (err) {
156
+ if ((0, errors_1.isForbidden)(err)) {
157
+ err.tables = readSetOf(execution, options);
158
+ err.keys = keySetOf(execution, options);
159
+ }
160
+ throw err;
161
+ }
162
+ };
163
+ queries.define({
164
+ name: (0, contract_1.pageQuery)(endpoint),
165
+ entity: options.entity ?? deps.fallbackEntity,
166
+ idField: options.idField,
167
+ tables: options.tables ?? [],
168
+ tracksReads: true,
169
+ run: async (wire, ctx) => {
170
+ const { args, offset, limit } = windowOf(wire, endpoint);
171
+ const outcome = await evaluate({ kind: "page", offset, limit }, args, ctx);
172
+ const result = shape(outcome.rows, outcome.execution, options, tracker, endpoint);
173
+ return {
174
+ ...result,
175
+ ...(outcome.order ? { order: outcome.order } : {}),
176
+ ...(outcome.filter ? { filter: outcome.filter } : {}),
177
+ };
178
+ },
179
+ });
180
+ queries.define({
181
+ name: (0, contract_1.countQuery)(endpoint),
182
+ entity: list_1.LIST_COUNT_ENTITY,
183
+ tables: options.tables ?? [],
184
+ tracksReads: true,
185
+ run: async (wire, ctx) => {
186
+ const args = positional(wire?.[0]);
187
+ const outcome = await evaluate({ kind: "count" }, args, ctx);
188
+ const tables = readSetOf(outcome.execution, options);
189
+ const keys = keySetOf(outcome.execution, options);
190
+ return {
191
+ // One row, so a total that changes is a field update on an object
192
+ // the browser already holds — the same thing every other live
193
+ // value is, rather than a number bolted onto the protocol.
194
+ rows: [{ id: (0, list_1.countRowId)(endpoint, args), total: outcome.total }],
195
+ single: true,
196
+ entity: list_1.LIST_COUNT_ENTITY,
197
+ ...(tables ? { tables } : {}),
198
+ ...(keys ? { keys } : {}),
199
+ };
200
+ },
201
+ });
202
+ }
203
+ /** `[args, offset, limit]` as the browser sends it, checked before it reaches the database. */
204
+ function windowOf(wire, endpoint) {
205
+ const [args, offset, limit] = (wire ?? []);
206
+ if (!isIndex(offset) || !isIndex(limit) || limit === 0) {
207
+ throw new Error(`"${endpoint}" was asked for the window (${String(offset)}, ${String(limit)}), ` +
208
+ `which is not a window.`);
209
+ }
210
+ if (limit > MAX_PAGE) {
211
+ throw new Error(`"${endpoint}" was asked for ${limit} rows at once; the most a single ` +
212
+ `window may hold is ${MAX_PAGE}. Lower the list's page size.`);
213
+ }
214
+ return { args: positional(args), offset, limit };
215
+ }
216
+ function isIndex(value) {
217
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
218
+ }
219
+ function positional(args) {
220
+ return Array.isArray(args) ? args : args === undefined ? [] : [args];
221
+ }
222
+ function readSetOf(execution, options) {
223
+ // "I could not tell" must stay distinguishable from "I read nothing".
224
+ if (execution.untracked)
225
+ return options.tables?.length ? [...options.tables] : undefined;
226
+ const tables = new Set([...execution.reads, ...(options.tables ?? [])]);
227
+ return tables.size ? [...tables] : undefined;
228
+ }
229
+ /**
230
+ * The read set narrowed to rows, when every read could be seen.
231
+ *
232
+ * Raw SQL forfeits the whole thing rather than half of it: a query that read
233
+ * something invisible to the tracker may depend on rows no key mentions, and a
234
+ * key set that is merely incomplete is the one shape of wrong this cannot
235
+ * afford. Tables named in `@query({ tables })` are watched whole for the same
236
+ * reason — a hand-declared dependency says which table, never which row.
237
+ */
238
+ function keySetOf(execution, options) {
239
+ if (execution.untracked || !execution.keys)
240
+ return undefined;
241
+ const keys = execution.keys.result();
242
+ for (const table of options.tables ?? [])
243
+ keys.set(table, types_1.ANY_ROWS);
244
+ return keys.size ? keys : undefined;
245
+ }
246
+ /** A query execution, with the read-set and read-key recorders armed. */
247
+ function queryExecution(ctx, tracker, list) {
248
+ return {
249
+ kind: "query",
250
+ session: ctx.session,
251
+ prisma: ctx.db.client,
252
+ reads: new Set(),
253
+ keys: new read_keys_1.KeyCollector({ tracker }),
254
+ untracked: false,
255
+ ...(list ? { list } : {}),
256
+ };
257
+ }
258
+ /**
259
+ * Turn whatever the method returned into rows the engine can diff.
260
+ *
261
+ * To-one relations pulled in by `include` are lifted out of their parent row and
262
+ * into `extra`, so they become shared instances in the client's identity map
263
+ * rather than copies embedded in a document. Two documents by the same author
264
+ * then observe one author object, and renaming them updates both.
265
+ */
266
+ function shape(returned, execution, options, tracker, name) {
267
+ const entity = options.entity ?? execution.lastModel;
268
+ const model = execution.lastModel;
269
+ const tables = readSetOf(execution, options);
270
+ const keys = tables ? keySetOf(execution, options) : undefined;
271
+ const single = !Array.isArray(returned);
272
+ const rows = toRows(returned, name);
273
+ const extra = {};
274
+ const flattened = model
275
+ ? rows.map((row) => lift(model, row, tracker, extra))
276
+ : rows;
277
+ return {
278
+ rows: flattened,
279
+ ...(Object.keys(extra).length ? { extra } : {}),
280
+ ...(tables ? { tables } : {}),
281
+ ...(keys ? { keys } : {}),
282
+ ...(entity ? { entity } : {}),
283
+ ...(single ? { single: true } : {}),
284
+ };
285
+ }
286
+ function toRows(returned, name) {
287
+ if (returned === null || returned === undefined)
288
+ return [];
289
+ if (Array.isArray(returned))
290
+ return returned;
291
+ if (typeof returned === "object")
292
+ return [returned];
293
+ throw new Error(`Query "${name}" returned ${typeof returned}. A live query must return rows — ` +
294
+ `an object, an array of objects, or null.`);
295
+ }
296
+ /** Move included to-one relations out of a row and into the shared entity sets. */
297
+ function lift(model, row, tracker, into) {
298
+ let out = null;
299
+ for (const [key, value] of Object.entries(row)) {
300
+ if (value === null || typeof value !== "object" || value instanceof Date)
301
+ continue;
302
+ const relation = tracker.relation(model, key);
303
+ // A to-many include stays where it is: it has no foreign key on this row
304
+ // to resolve it back through, so lifting it would lose the association.
305
+ if (!relation || relation.isList || Array.isArray(value))
306
+ continue;
307
+ const target = relation.target;
308
+ const nested = lift(target, value, tracker, into);
309
+ (into[target] ?? (into[target] = [])).push(nested);
310
+ out ?? (out = { ...row });
311
+ delete out[key];
312
+ }
313
+ return out ?? row;
314
+ }
315
+ function entityDescriptors(tracker) {
316
+ const out = {};
317
+ for (const model of tracker.models()) {
318
+ const relations = {};
319
+ for (const relation of tracker.relationsOf(model)) {
320
+ if (relation.isList || !relation.localKey)
321
+ continue;
322
+ relations[relation.field] = { entity: relation.target, localKey: relation.localKey };
323
+ }
324
+ out[model] = {
325
+ idField: tracker.idField(model),
326
+ ...(Object.keys(relations).length ? { relations } : {}),
327
+ };
328
+ }
329
+ return out;
330
+ }
@@ -0,0 +1,25 @@
1
+ import type { ServerWelcome } from "../../core/protocol";
2
+ import { type SsrReader } from "../../core/ssr-bridge";
3
+ import type { SnapshotRunner } from "../db";
4
+ import type { QueryRegistry, SessionInfo } from "../query";
5
+ export interface SsrCollectorDeps {
6
+ snapshots: SnapshotRunner;
7
+ queries: QueryRegistry;
8
+ manifest?: ServerWelcome["api"];
9
+ /**
10
+ * How long the snapshot may stay open.
11
+ *
12
+ * A render that never finishes must not hold a database transaction with it —
13
+ * the Prisma runner's own transaction timeout would fire anyway, and it would
14
+ * fire as an unexplained error inside whatever query happened to be next.
15
+ */
16
+ timeoutMs?: number;
17
+ }
18
+ export interface SsrCollector extends SsrReader {
19
+ /** The handle a client component uses to find this reader. */
20
+ readonly id: string;
21
+ /** Release the snapshot. Idempotent, and safe to call while reads are in flight. */
22
+ close(): Promise<void>;
23
+ }
24
+ export declare function openSsrCollector(deps: SsrCollectorDeps, session: SessionInfo): SsrCollector;
25
+ //# sourceMappingURL=collector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collector.d.ts","sourceRoot":"","sources":["../../../src/server/api/collector.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAoB,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAkD,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvG,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,OAAO,CAAC;AAE7D,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAC7B,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,aAAa,CAAC;IACvB,QAAQ,CAAC,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;IAChC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC3C,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,oFAAoF;IACpF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,GAAG,YAAY,CAsH3F"}