@jam-overture/loom 0.2.0 → 0.3.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 (194) hide show
  1. package/dist/audience/compose.d.ts +112 -0
  2. package/dist/audience/compose.js +134 -0
  3. package/dist/audience/memory.d.ts +14 -0
  4. package/dist/audience/memory.js +71 -0
  5. package/dist/audience/overlay-store.d.ts +343 -0
  6. package/dist/audience/overlay-store.js +217 -0
  7. package/dist/audience/rule.d.ts +121 -0
  8. package/dist/audience/rule.js +78 -0
  9. package/dist/cli/index.d.ts +3 -4
  10. package/dist/cli/index.js +3 -4
  11. package/dist/data/adapter.d.ts +9 -1
  12. package/dist/data/adapter.js +2 -0
  13. package/dist/data/resolve.d.ts +1 -1
  14. package/dist/interpretation/anthropic.d.ts +1 -1
  15. package/dist/interpretation/anthropic.js +2 -22
  16. package/dist/interpretation/client.d.ts +1 -1
  17. package/dist/interpretation/materialize.js +67 -22
  18. package/dist/interpretation/openai-compatible.d.ts +36 -0
  19. package/dist/interpretation/openai-compatible.js +79 -0
  20. package/dist/interpretation/status.d.ts +19 -0
  21. package/dist/interpretation/status.js +26 -0
  22. package/dist/live/index.d.ts +73 -0
  23. package/dist/live/index.js +73 -0
  24. package/dist/live/pages.d.ts +187 -0
  25. package/dist/live/pages.js +161 -0
  26. package/dist/live/pull.d.ts +147 -0
  27. package/dist/live/pull.js +398 -0
  28. package/dist/live/pulling.d.ts +79 -0
  29. package/dist/live/pulling.js +117 -0
  30. package/dist/live/window.d.ts +129 -0
  31. package/dist/live/window.js +132 -0
  32. package/dist/render/addressed.d.ts +35 -0
  33. package/dist/render/addressed.js +79 -0
  34. package/dist/render/document-theme.d.ts +70 -0
  35. package/dist/render/document-theme.js +139 -0
  36. package/dist/render/editable.d.ts +15 -1
  37. package/dist/render/editable.js +13 -1
  38. package/dist/render/expected.d.ts +98 -0
  39. package/dist/render/expected.js +88 -0
  40. package/dist/render/index.d.ts +2 -0
  41. package/dist/render/index.js +2 -0
  42. package/dist/render/render.d.ts +11 -0
  43. package/dist/render/render.js +192 -46
  44. package/dist/render/request.d.ts +8 -1
  45. package/dist/render/request.js +1 -0
  46. package/dist/runtime/auto-apply-ceiling.d.ts +54 -0
  47. package/dist/runtime/auto-apply-ceiling.js +66 -0
  48. package/dist/runtime/gate.js +69 -10
  49. package/dist/runtime/index.d.ts +1 -0
  50. package/dist/runtime/index.js +1 -0
  51. package/dist/runtime/nesting.d.ts +13 -1
  52. package/dist/runtime/nesting.js +41 -24
  53. package/dist/runtime/policy-change.js +8 -2
  54. package/dist/runtime/policy-log.d.ts +5 -5
  55. package/dist/runtime/policy.d.ts +8 -6
  56. package/dist/runtime/policy.js +5 -2
  57. package/dist/runtime/repointing.js +0 -0
  58. package/dist/sdk/definition.d.ts +65 -6
  59. package/dist/sdk/definition.js +44 -0
  60. package/dist/sdk/registry.d.ts +17 -1
  61. package/dist/sdk/registry.js +39 -0
  62. package/dist/signals/acted.contract.d.ts +21 -0
  63. package/dist/signals/acted.contract.js +236 -0
  64. package/dist/signals/acted.d.ts +359 -0
  65. package/dist/signals/acted.js +135 -0
  66. package/dist/signals/agenda.d.ts +585 -0
  67. package/dist/signals/agenda.js +295 -0
  68. package/dist/signals/arrivals.contract.d.ts +21 -0
  69. package/dist/signals/arrivals.contract.js +180 -0
  70. package/dist/signals/arrivals.d.ts +375 -0
  71. package/dist/signals/arrivals.js +254 -0
  72. package/dist/signals/broadcast.d.ts +25 -15
  73. package/dist/signals/broadcast.js +209 -36
  74. package/dist/signals/collect.d.ts +137 -43
  75. package/dist/signals/collect.js +103 -36
  76. package/dist/signals/conversion.d.ts +348 -0
  77. package/dist/signals/conversion.js +235 -0
  78. package/dist/signals/correlated.contract.d.ts +24 -0
  79. package/dist/signals/correlated.contract.js +94 -0
  80. package/dist/signals/counters.d.ts +51 -0
  81. package/dist/signals/counters.js +58 -0
  82. package/dist/signals/deployment-change.d.ts +28 -4
  83. package/dist/signals/deployment-change.js +57 -16
  84. package/dist/signals/deployment.d.ts +18 -5
  85. package/dist/signals/deployment.js +37 -11
  86. package/dist/signals/door.d.ts +34 -12
  87. package/dist/signals/door.js +37 -13
  88. package/dist/signals/expire.d.ts +192 -0
  89. package/dist/signals/expire.js +213 -0
  90. package/dist/signals/frontier.d.ts +268 -0
  91. package/dist/signals/frontier.js +145 -0
  92. package/dist/signals/funnel-hours.contract.d.ts +21 -0
  93. package/dist/signals/funnel-hours.contract.js +221 -0
  94. package/dist/signals/funnel-hours.d.ts +293 -0
  95. package/dist/signals/funnel-hours.js +99 -0
  96. package/dist/signals/funnel.d.ts +60 -0
  97. package/dist/signals/funnel.js +35 -20
  98. package/dist/signals/health.d.ts +201 -4
  99. package/dist/signals/health.js +214 -2
  100. package/dist/signals/index.d.ts +19 -0
  101. package/dist/signals/index.js +19 -0
  102. package/dist/signals/inside.d.ts +190 -0
  103. package/dist/signals/inside.js +263 -0
  104. package/dist/signals/join.d.ts +56 -0
  105. package/dist/signals/join.js +60 -0
  106. package/dist/signals/journal.d.ts +112 -9
  107. package/dist/signals/kept.contract.d.ts +22 -0
  108. package/dist/signals/kept.contract.js +111 -0
  109. package/dist/signals/library-agenda-change.d.ts +324 -0
  110. package/dist/signals/library-agenda-change.js +199 -0
  111. package/dist/signals/library-agenda.d.ts +258 -0
  112. package/dist/signals/library-agenda.js +167 -0
  113. package/dist/signals/library-reach-change.d.ts +10 -0
  114. package/dist/signals/library-reach-change.js +11 -3
  115. package/dist/signals/library-senders-change.d.ts +457 -0
  116. package/dist/signals/library-senders-change.js +367 -0
  117. package/dist/signals/library-senders-reach-change.d.ts +486 -0
  118. package/dist/signals/library-senders-reach-change.js +538 -0
  119. package/dist/signals/library-senders-reach.d.ts +340 -0
  120. package/dist/signals/library-senders-reach.js +252 -0
  121. package/dist/signals/library-senders.d.ts +271 -0
  122. package/dist/signals/library-senders.js +180 -0
  123. package/dist/signals/library-word-reach-change.js +2 -6
  124. package/dist/signals/memory.js +142 -1
  125. package/dist/signals/migrate.d.ts +6 -5
  126. package/dist/signals/migrate.js +150 -6
  127. package/dist/signals/notice.d.ts +88 -33
  128. package/dist/signals/notice.js +38 -16
  129. package/dist/signals/part-pace.d.ts +378 -0
  130. package/dist/signals/part-pace.js +333 -0
  131. package/dist/signals/parts.d.ts +25 -15
  132. package/dist/signals/parts.js +32 -73
  133. package/dist/signals/postgres.js +400 -26
  134. package/dist/signals/region.d.ts +1 -1
  135. package/dist/signals/retention.d.ts +43 -21
  136. package/dist/signals/retention.js +25 -8
  137. package/dist/signals/rhythm.d.ts +302 -0
  138. package/dist/signals/rhythm.js +262 -0
  139. package/dist/signals/rollup.d.ts +127 -1
  140. package/dist/signals/rollup.js +211 -24
  141. package/dist/signals/schema.d.ts +640 -3
  142. package/dist/signals/schema.js +239 -3
  143. package/dist/signals/silences.d.ts +310 -11
  144. package/dist/signals/silences.js +243 -0
  145. package/dist/signals/subtrees.d.ts +123 -0
  146. package/dist/signals/subtrees.js +102 -0
  147. package/dist/signals/tally.d.ts +125 -4
  148. package/dist/signals/unread.d.ts +292 -0
  149. package/dist/signals/unread.js +137 -0
  150. package/dist/signals/window-agenda.d.ts +276 -0
  151. package/dist/signals/window-agenda.js +83 -0
  152. package/dist/signals/window-funnels.d.ts +88 -0
  153. package/dist/signals/window-funnels.js +47 -0
  154. package/dist/store/cache.d.ts +101 -0
  155. package/dist/store/cache.js +149 -0
  156. package/dist/store/history.d.ts +82 -0
  157. package/dist/store/history.js +36 -0
  158. package/dist/store/index.d.ts +11 -0
  159. package/dist/store/index.js +11 -0
  160. package/dist/store/migrate.d.ts +26 -0
  161. package/dist/store/migrate.js +64 -0
  162. package/dist/store/postgres-audience.d.ts +14 -0
  163. package/dist/store/postgres-audience.js +272 -0
  164. package/dist/store/postgres.d.ts +1 -0
  165. package/dist/store/postgres.js +1 -0
  166. package/dist/store/schema.d.ts +312 -0
  167. package/dist/store/schema.js +77 -0
  168. package/dist/store/source.d.ts +57 -1
  169. package/dist/store/source.js +65 -1
  170. package/dist/submit/resolve.d.ts +1 -1
  171. package/dist/telemetry/index.d.ts +1 -0
  172. package/dist/telemetry/index.js +1 -0
  173. package/dist/telemetry/journal.d.ts +32 -0
  174. package/dist/telemetry/memory.js +10 -1
  175. package/dist/telemetry/postgres.js +18 -2
  176. package/dist/telemetry/window.d.ts +135 -0
  177. package/dist/telemetry/window.js +101 -0
  178. package/dist/testing/audience-overlay-contract.d.ts +31 -0
  179. package/dist/testing/audience-overlay-contract.js +354 -0
  180. package/dist/testing/contracts.d.ts +1 -0
  181. package/dist/testing/contracts.js +1 -0
  182. package/dist/testing/journal-contract.js +158 -5
  183. package/dist/theme/contrast.d.ts +19 -14
  184. package/dist/theme/contrast.js +181 -17
  185. package/dist/tree/apply.js +13 -0
  186. package/dist/tree/mutation.d.ts +18 -0
  187. package/dist/tree/mutation.js +24 -12
  188. package/dist/tree/navigation.d.ts +5 -0
  189. package/dist/tree/navigation.js +32 -10
  190. package/dist/tree/outline.d.ts +7 -0
  191. package/dist/tree/outline.js +9 -5
  192. package/package.json +39 -96
  193. package/dist/runtime/inverse-interpreter.d.ts +0 -90
  194. package/dist/runtime/inverse-interpreter.js +0 -56
@@ -0,0 +1,36 @@
1
+ import type { ModelClient } from "./client.js";
2
+ /**
3
+ * The adapter for any server that speaks the OpenAI-compatible chat API with
4
+ * JSON-schema replies: vLLM, llama.cpp's server, Ollama, and the hosted
5
+ * services that serve open models the same way. Like `anthropic.ts` it is an
6
+ * entry point of its own, not exported from the package root (0005), and its
7
+ * whole job is translation.
8
+ *
9
+ * It takes `fetch` rather than a vendor SDK, so it adds no dependency, and so
10
+ * a host decides what the network may reach: the portal hands it a `fetch`
11
+ * that refuses private addresses (0421 clause 6).
12
+ *
13
+ * `effort` has no counterpart in this API that every such server honours, so
14
+ * it is not sent. A server that cannot hold to the schema answers with text
15
+ * the interpreter cannot parse, which it already reports as a malformed reply.
16
+ */
17
+ /** The part of `fetch` this adapter uses, so a host can hand it a guarded one and a test a stub. */
18
+ export type CompatibleFetch = (url: string, init: {
19
+ readonly method: "POST";
20
+ readonly headers: Readonly<Record<string, string>>;
21
+ readonly body: string;
22
+ readonly redirect: "error";
23
+ readonly signal?: AbortSignal | undefined;
24
+ }) => Promise<{
25
+ readonly status: number;
26
+ readonly json: () => Promise<unknown>;
27
+ }>;
28
+ export type OpenAiCompatibleConfig = {
29
+ /** The server's API root, such as `https://models.example.com/v1`; `/chat/completions` is added. */
30
+ readonly endpoint: string;
31
+ /** Sent as a bearer token where the server asks for one. */
32
+ readonly apiKey?: string | undefined;
33
+ readonly fetch: CompatibleFetch;
34
+ };
35
+ export declare const openAiCompatibleModelClient: (config: OpenAiCompatibleConfig) => ModelClient;
36
+ //# sourceMappingURL=openai-compatible.d.ts.map
@@ -0,0 +1,79 @@
1
+ import { z } from "zod";
2
+ import { err, ok } from "../result.js";
3
+ import { classifyStatus } from "./status.js";
4
+ const replySchema = z.object({
5
+ model: z.string().optional(),
6
+ choices: z
7
+ .array(z.object({
8
+ finish_reason: z.string().nullable().optional(),
9
+ message: z.object({
10
+ content: z.string().nullable().optional(),
11
+ refusal: z.string().nullable().optional(),
12
+ }),
13
+ }))
14
+ .min(1),
15
+ });
16
+ /** What a reply the server finished says, as a completion or the reason it is not one. Pure. */
17
+ const completionOf = (reply, asked) => {
18
+ const [choice] = reply.choices;
19
+ if (choice === undefined)
20
+ return err({ code: "incomplete", detail: "reply had no choices" });
21
+ const refusal = choice.message.refusal ?? undefined;
22
+ if (refusal !== undefined || choice.finish_reason === "content_filter") {
23
+ return err({ code: "refused", detail: refusal ?? "content_filter" });
24
+ }
25
+ if (choice.finish_reason === "length") {
26
+ return err({ code: "incomplete", detail: "hit the output token ceiling" });
27
+ }
28
+ const text = choice.message.content ?? undefined;
29
+ if (text === undefined || text === "") {
30
+ return err({ code: "incomplete", detail: "reply contained no text" });
31
+ }
32
+ return ok({ text, servedBy: reply.model ?? asked });
33
+ };
34
+ /** The request body, as the chat API spells it. Pure. */
35
+ const bodyOf = (request) => JSON.stringify({
36
+ model: request.model,
37
+ max_tokens: request.maxTokens,
38
+ messages: [
39
+ { role: "system", content: request.system },
40
+ { role: "user", content: request.userMessage },
41
+ ],
42
+ response_format: {
43
+ type: "json_schema",
44
+ json_schema: { name: "loom_reply", schema: request.outputSchema, strict: true },
45
+ },
46
+ });
47
+ const errorDetail = (cause) => cause instanceof Error ? cause.message : "unknown transport failure";
48
+ export const openAiCompatibleModelClient = (config) => {
49
+ const url = `${config.endpoint.replace(/\/+$/u, "")}/chat/completions`;
50
+ const headers = {
51
+ "content-type": "application/json",
52
+ ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
53
+ };
54
+ return {
55
+ complete: async (request, options) => {
56
+ try {
57
+ const response = await config.fetch(url, {
58
+ method: "POST",
59
+ headers,
60
+ body: bodyOf(request),
61
+ /** A server that redirects is answered as one that refused, never followed (0421). */
62
+ redirect: "error",
63
+ signal: options?.signal,
64
+ });
65
+ if (response.status < 200 || response.status >= 300) {
66
+ return err({ code: classifyStatus(response.status), detail: `status ${response.status}` });
67
+ }
68
+ const reply = replySchema.safeParse(await response.json());
69
+ return reply.success
70
+ ? completionOf(reply.data, request.model)
71
+ : err({ code: "incomplete", detail: "reply was not a chat completion" });
72
+ }
73
+ catch (cause) {
74
+ return err({ code: "unavailable", detail: errorDetail(cause) });
75
+ }
76
+ },
77
+ };
78
+ };
79
+ //# sourceMappingURL=openai-compatible.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What an HTTP status from a model's service means for the caller, shared by
3
+ * every adapter so that a 429 means the same thing whichever vendor sent it.
4
+ */
5
+ /**
6
+ * Which of the three "could not answer" codes a failed call is, by its status.
7
+ *
8
+ * Only a status we positively recognise as this side's fault becomes `rejected`
9
+ * or `misconfigured`; everything else — including a transport failure that
10
+ * never got a response — stays `unavailable`. Guessing wrong in that direction
11
+ * costs a retry that fails, where guessing wrong the other way tells a host to
12
+ * stop trying something that would have worked.
13
+ *
14
+ * 408, 409 and 429 are the 4xx statuses that mean "later". The Anthropic SDK
15
+ * has already retried them twice by the time one reaches here, so a 429 that
16
+ * escapes it is a rate limit that outlasted the client's own backoff.
17
+ */
18
+ export declare const classifyStatus: (status: number | undefined) => "unavailable" | "rejected" | "misconfigured";
19
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What an HTTP status from a model's service means for the caller, shared by
3
+ * every adapter so that a 429 means the same thing whichever vendor sent it.
4
+ */
5
+ /**
6
+ * Which of the three "could not answer" codes a failed call is, by its status.
7
+ *
8
+ * Only a status we positively recognise as this side's fault becomes `rejected`
9
+ * or `misconfigured`; everything else — including a transport failure that
10
+ * never got a response — stays `unavailable`. Guessing wrong in that direction
11
+ * costs a retry that fails, where guessing wrong the other way tells a host to
12
+ * stop trying something that would have worked.
13
+ *
14
+ * 408, 409 and 429 are the 4xx statuses that mean "later". The Anthropic SDK
15
+ * has already retried them twice by the time one reaches here, so a 429 that
16
+ * escapes it is a rate limit that outlasted the client's own backoff.
17
+ */
18
+ export const classifyStatus = (status) => {
19
+ if (status === undefined)
20
+ return "unavailable";
21
+ if (status === 401 || status === 402 || status === 403)
22
+ return "misconfigured";
23
+ const asksAgainLater = status === 408 || status === 409 || status === 429;
24
+ return status >= 400 && status < 500 && !asksAgainLater ? "rejected" : "unavailable";
25
+ };
26
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The half of going live that runs in the customer's server.
3
+ *
4
+ * A change accepted in the portal is live as soon as the site next pulls
5
+ * (0358): there is no pull request, no merge and no deploy between somebody
6
+ * accepting a change and a reader seeing it. What makes that true is this —
7
+ * a loop that fetches the project's live pages from Loom on a short interval,
8
+ * keeps them in the process, and hands one to the render path by page id.
9
+ *
10
+ * Three properties hold by construction rather than by care, and each has a
11
+ * test that would fail if it stopped:
12
+ *
13
+ * - **Loom is in the render path once per server, and only until it answers**
14
+ * (0262, 0364). The first reader on a new server waits for the first pull,
15
+ * so they get the live page rather than one that changes on their next
16
+ * request; a failed pull ends the wait at once and a silent Loom ends it after
17
+ * `DEFAULT_FIRST_WAIT_MS`. Every pull after that runs beside requests, on a
18
+ * timer, and no reader waits on it.
19
+ * - **Loom never learns who a reader is.** The request carries the project's
20
+ * key and the tag of what is held, and nothing else. The door answers every
21
+ * page's segment rules and segment forms beside the pages (0371), and both
22
+ * sorting a reader into a segment and composing the page they get happen
23
+ * afterwards, here, against rules and deltas already held: `pageForReader`
24
+ * reads the context the host's server built and answers a tree and a
25
+ * segment's name, and nothing about the reader leaves the process.
26
+ * - **A failed pull costs freshness, never the page** (0358 clause 4). Every
27
+ * way a pull can fail leaves the last pages whole, and a server with none
28
+ * renders every page as it was built.
29
+ *
30
+ * ```ts
31
+ * const live = startPullingLivePages({
32
+ * deployment: process.env.LOOM_URL ?? "",
33
+ * key: process.env.LOOM_PROJECT_KEY ?? "",
34
+ * onOutcome: (outcome) => {
35
+ * if (outcome.kind === "failed") log.warn(describeSitePullFailure(outcome.failure))
36
+ * },
37
+ * })
38
+ *
39
+ * // wherever a page is rendered, with the tree the site was built with, and
40
+ * // what this server knows about the request in the keys the rules read
41
+ * const held = await live.ready()
42
+ * const pin = pinIn(request.headers.get("cookie"))
43
+ * const served = pageForReader(held, builtTree, { device: "phone", returning: true }, pin)
44
+ * const keep = pinCookieFor(held, pin)
45
+ *
46
+ * if (served.refusal !== undefined) log.warn(describeComposeError(served.refusal))
47
+ * if (keep !== undefined) response.headers.set("set-cookie", keep)
48
+ *
49
+ * renderLoomTree(served.tree, { resolver, addressed: true, audience: served.audience })
50
+ * ```
51
+ *
52
+ * The last two of those are what a project with a reader window costs a host
53
+ * (0383): a reader keeps the pages they first saw for as long as the project
54
+ * set, and a project with no window — which is every project until somebody
55
+ * chooses one — needs neither line. Both are pure, both read only what the last
56
+ * pull brought, and nothing about the reader leaves the process.
57
+ *
58
+ * The page's signals are filed under the segment it was rendered for (0284):
59
+ * the root carries it, and the broadcaster reads it from there.
60
+ */
61
+ /**
62
+ * The refusal a composition hands back, and the sentence for it, re-exported
63
+ * here because the place a host meets one is the render path. A site's server
64
+ * imports `/live` and `/react`; making it import the control plane's door to
65
+ * say why a page was served as the base would be the wrong dependency for the
66
+ * one line of logging this costs.
67
+ */
68
+ export { describeComposeError, type AudienceForm, type ComposeError } from "../audience/compose.js";
69
+ export { isPulling, livePageOf, livePagesHeld, NO_LIVE_PAGES, pageForReader, segmentOf, type LivePages, type ServedPage, } from "./pages.js";
70
+ export { PIN_COOKIE, pinCookieFor, pinIn, WINDOW_OFF, type HeldVersion, type LiveWindow, } from "./window.js";
71
+ export { describeSitePullFailure, DEFAULT_PULL_CEILING_MS, LIVE_PAGES_PATH, livePagesUrlOf, pullLivePages, withPullOutcome, type LivePageForms, type LivePageRules, type PullFetch, type PullLivePagesOptions, type SitePullFailure, type SitePullOutcome, } from "./pull.js";
72
+ export { DEFAULT_FIRST_WAIT_MS, DEFAULT_PULL_INTERVAL_MS, startPullingLivePages, type LivePullLoop, type PullSchedule, type StartPullingOptions, } from "./pulling.js";
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The half of going live that runs in the customer's server.
3
+ *
4
+ * A change accepted in the portal is live as soon as the site next pulls
5
+ * (0358): there is no pull request, no merge and no deploy between somebody
6
+ * accepting a change and a reader seeing it. What makes that true is this —
7
+ * a loop that fetches the project's live pages from Loom on a short interval,
8
+ * keeps them in the process, and hands one to the render path by page id.
9
+ *
10
+ * Three properties hold by construction rather than by care, and each has a
11
+ * test that would fail if it stopped:
12
+ *
13
+ * - **Loom is in the render path once per server, and only until it answers**
14
+ * (0262, 0364). The first reader on a new server waits for the first pull,
15
+ * so they get the live page rather than one that changes on their next
16
+ * request; a failed pull ends the wait at once and a silent Loom ends it after
17
+ * `DEFAULT_FIRST_WAIT_MS`. Every pull after that runs beside requests, on a
18
+ * timer, and no reader waits on it.
19
+ * - **Loom never learns who a reader is.** The request carries the project's
20
+ * key and the tag of what is held, and nothing else. The door answers every
21
+ * page's segment rules and segment forms beside the pages (0371), and both
22
+ * sorting a reader into a segment and composing the page they get happen
23
+ * afterwards, here, against rules and deltas already held: `pageForReader`
24
+ * reads the context the host's server built and answers a tree and a
25
+ * segment's name, and nothing about the reader leaves the process.
26
+ * - **A failed pull costs freshness, never the page** (0358 clause 4). Every
27
+ * way a pull can fail leaves the last pages whole, and a server with none
28
+ * renders every page as it was built.
29
+ *
30
+ * ```ts
31
+ * const live = startPullingLivePages({
32
+ * deployment: process.env.LOOM_URL ?? "",
33
+ * key: process.env.LOOM_PROJECT_KEY ?? "",
34
+ * onOutcome: (outcome) => {
35
+ * if (outcome.kind === "failed") log.warn(describeSitePullFailure(outcome.failure))
36
+ * },
37
+ * })
38
+ *
39
+ * // wherever a page is rendered, with the tree the site was built with, and
40
+ * // what this server knows about the request in the keys the rules read
41
+ * const held = await live.ready()
42
+ * const pin = pinIn(request.headers.get("cookie"))
43
+ * const served = pageForReader(held, builtTree, { device: "phone", returning: true }, pin)
44
+ * const keep = pinCookieFor(held, pin)
45
+ *
46
+ * if (served.refusal !== undefined) log.warn(describeComposeError(served.refusal))
47
+ * if (keep !== undefined) response.headers.set("set-cookie", keep)
48
+ *
49
+ * renderLoomTree(served.tree, { resolver, addressed: true, audience: served.audience })
50
+ * ```
51
+ *
52
+ * The last two of those are what a project with a reader window costs a host
53
+ * (0383): a reader keeps the pages they first saw for as long as the project
54
+ * set, and a project with no window — which is every project until somebody
55
+ * chooses one — needs neither line. Both are pure, both read only what the last
56
+ * pull brought, and nothing about the reader leaves the process.
57
+ *
58
+ * The page's signals are filed under the segment it was rendered for (0284):
59
+ * the root carries it, and the broadcaster reads it from there.
60
+ */
61
+ /**
62
+ * The refusal a composition hands back, and the sentence for it, re-exported
63
+ * here because the place a host meets one is the render path. A site's server
64
+ * imports `/live` and `/react`; making it import the control plane's door to
65
+ * say why a page was served as the base would be the wrong dependency for the
66
+ * one line of logging this costs.
67
+ */
68
+ export { describeComposeError } from "../audience/compose.js";
69
+ export { isPulling, livePageOf, livePagesHeld, NO_LIVE_PAGES, pageForReader, segmentOf, } from "./pages.js";
70
+ export { PIN_COOKIE, pinCookieFor, pinIn, WINDOW_OFF, } from "./window.js";
71
+ export { describeSitePullFailure, DEFAULT_PULL_CEILING_MS, LIVE_PAGES_PATH, livePagesUrlOf, pullLivePages, withPullOutcome, } from "./pull.js";
72
+ export { DEFAULT_FIRST_WAIT_MS, DEFAULT_PULL_INTERVAL_MS, startPullingLivePages, } from "./pulling.js";
73
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,187 @@
1
+ /**
2
+ * The live pages a customer's server holds, and the one question a render asks
3
+ * of them.
4
+ *
5
+ * Loom is not in the render path (0262), so a page that an accepted change has
6
+ * moved cannot be fetched while a reader waits for it. What the server does
7
+ * instead is keep the project's live pages in its own process and draw from
8
+ * what it holds — and this is that holding, as a value rather than as a mutable
9
+ * cache. Every pull produces a new one; nothing here is edited in place, so a
10
+ * render that has already read a page cannot have it changed underneath.
11
+ *
12
+ * **A page this does not hold is not an error.** `livePageOf` answers
13
+ * `undefined`, and the caller renders the page as it was built. That is the
14
+ * whole of the fallback a host has to write, and it is the same answer for a
15
+ * server that has never pulled, a pull that failed, and a page the answer did
16
+ * not name.
17
+ */
18
+ import type { AudienceId } from "../audience/audience.js";
19
+ import { type AudienceForm, type ComposeError } from "../audience/compose.js";
20
+ import { type AudienceRule } from "../audience/rule.js";
21
+ import type { TreeId } from "../ids.js";
22
+ import type { JsonObject } from "../json.js";
23
+ import type { LoomTree } from "../tree/tree.js";
24
+ import { type LiveWindow } from "./window.js";
25
+ /**
26
+ * What a pull leaves behind: the pages, the rules that sort their readers, the
27
+ * tag that names both, and enough of the last outcome to say whether the site
28
+ * is current.
29
+ *
30
+ * The tag, the pages and the rules travel together by construction. A pull that
31
+ * cannot be read moves none of them, so the tag always names what is held beside
32
+ * it — which is what makes it safe to send back as `If-None-Match` — and a site
33
+ * never sorts readers by one pull's rules on another pull's pages (0371 clause
34
+ * 4).
35
+ */
36
+ export type LivePages = {
37
+ /** The live pages, by the id of the page each one is. */
38
+ readonly pages: ReadonlyMap<TreeId, LoomTree>;
39
+ /**
40
+ * Each live page's segment rules, in the order the portal set. A page with
41
+ * none is absent, and every reader of it is in no segment (0371).
42
+ */
43
+ readonly rules: ReadonlyMap<TreeId, readonly AudienceRule[]>;
44
+ /**
45
+ * Each live page's segment forms: the delta one segment's readers are served
46
+ * over the base (0263, 0371). A page with none is absent,
47
+ * and so is a segment that is only a name — which is what every segment was
48
+ * before the door answered forms.
49
+ */
50
+ readonly forms: ReadonlyMap<TreeId, readonly AudienceForm[]>;
51
+ /**
52
+ * How long this project holds its readers, and each page's versions a pin can
53
+ * still be served (0383). `WINDOW_OFF` where nobody chose a window, and for a
54
+ * door from before the window answered one.
55
+ */
56
+ readonly window: LiveWindow;
57
+ /** The entity tag the door gave for exactly these pages, if it gave one. */
58
+ readonly tag: string | undefined;
59
+ /** When the door last answered, whether it answered pages or `304`. */
60
+ readonly pulledAt: number | undefined;
61
+ /** When these pages arrived, which is older than `pulledAt` after a `304`. */
62
+ readonly freshAt: number | undefined;
63
+ /** Failed pulls since the last one the door answered. Zero while current. */
64
+ readonly failures: number;
65
+ };
66
+ /**
67
+ * A server that has not pulled yet, which is every server at the moment it
68
+ * starts.
69
+ *
70
+ * It renders every page as built, so a deployment whose pull is misconfigured
71
+ * serves its site rather than an error — the property the pull exists to keep
72
+ * (0358 clause 4) is true before the first pull as well as after a failed one.
73
+ */
74
+ export declare const NO_LIVE_PAGES: LivePages;
75
+ /**
76
+ * The live page for this page id, or `undefined` to render the page as built.
77
+ *
78
+ * This is the only call a render path makes. Selection for an audience (0263)
79
+ * happens after it, in the customer's process, against the tree this answers —
80
+ * the pull carries no audience and the door refuses a request that names one.
81
+ *
82
+ * **With a reader's pin, the version they were pinned to** (0383 clause 2),
83
+ * which is the newest version of this page live at or before the pin. A pin the
84
+ * server cannot resolve, and a page it holds no earlier version of, read the
85
+ * newest live page; so does every reader of a project with no window, which is
86
+ * every project until one is chosen. `pinIn` reads the pin from the request's
87
+ * `Cookie` header and nothing about the reader goes any further than this call.
88
+ *
89
+ * The pin is an optional argument rather than a second function because the
90
+ * question is one question — *what do I draw for this reader* — and a host that
91
+ * honours a window should not have a second call to remember on each page.
92
+ */
93
+ export declare const livePageOf: (held: LivePages, page: TreeId, pin?: number) => LoomTree | undefined;
94
+ /**
95
+ * The segment this reader of this page is in, or `undefined` for none — which
96
+ * is `aud_everyone`, and is what a page with no rules answers for every reader.
97
+ *
98
+ * **Decided here, in the site's process, and never sent anywhere** (0262,
99
+ * 0371 clause 2). The context is whatever the host's server knows while it
100
+ * draws the page — `device`, `source`, `returning`, the keys its rules were
101
+ * written against — and none of it leaves this function: what comes out is a
102
+ * segment's name, which the host stamps on the page it renders so the page's
103
+ * signals are filed under it (0284).
104
+ *
105
+ * **One segment, the last rule that matches** (0385). A batch names one
106
+ * audience, so a reader two rules match is counted in one segment rather than
107
+ * in both, which would count one page view twice wherever segments are added
108
+ * up. The last rule is the one the portal orders general to specific, and the
109
+ * one that wins a contested part of the page (0359 clause 3), so it is the form
110
+ * the reader will be served once a segment has a form of its own.
111
+ *
112
+ * **This answers the name a signal is filed under, not the page that is
113
+ * served.** Which deltas a reader gets is `pageForReader`, and it is not the
114
+ * same question: a reader two rules match is in one segment for counting and
115
+ * is served both of their forms, in the deployment's order (0359 clause 3).
116
+ */
117
+ export declare const segmentOf: (held: LivePages, page: TreeId, context: JsonObject | undefined) => AudienceId | undefined;
118
+ /**
119
+ * A page as one reader gets it: what to render, and what to call them while
120
+ * they read it.
121
+ */
122
+ export type ServedPage = {
123
+ /** The tree to render — the live page with this reader's forms applied. */
124
+ readonly tree: LoomTree;
125
+ /**
126
+ * The segment to file this page view under (0284), or `undefined` for
127
+ * `aud_everyone`. Absent after a refusal, because the reader got the base.
128
+ */
129
+ readonly audience: AudienceId | undefined;
130
+ /**
131
+ * Why the forms were not applied, for the host's log. `undefined` on every
132
+ * request a deployment intends, including every request of a page with no
133
+ * segments at all.
134
+ */
135
+ readonly refusal: ComposeError | undefined;
136
+ };
137
+ /**
138
+ * What to render for this reader, and what to file their signals under.
139
+ *
140
+ * The one call a render path makes once a deployment has segments: it answers
141
+ * the live page composed with the forms this reader's segments earn, the
142
+ * segment's name for the page's signals, and — where the forms could not be
143
+ * applied — why.
144
+ *
145
+ * **A form that cannot be applied costs the reader their segment, not their
146
+ * page.** The two properties either side of this are both worth keeping and
147
+ * they pull apart exactly here. A pull that fails costs freshness and never the
148
+ * page (0358 clause 4), so there is always something to render. A composition
149
+ * refuses rather than falling back to the base (0263 clause 4), because a
150
+ * reader served the base whose page views are filed under `aud_eu` makes the
151
+ * comparison between two segments a comparison between one segment's form and
152
+ * another segment's *name over the base*.
153
+ *
154
+ * Dropping the audience keeps both: the reader gets the base page, their
155
+ * signals say what they were actually shown, and the deployment's figures stay
156
+ * a comparison of forms readers were served. The refusal is handed back rather
157
+ * than swallowed because a segment whose form has gone stale is a thing
158
+ * somebody must be told about — it is silent otherwise, and silently serving
159
+ * the base is the state 0263 clause 4 refuses.
160
+ *
161
+ * A deployment with no segments, a reader the rules do not match, and a server
162
+ * that has never pulled all answer the same way: the page, and no segment.
163
+ *
164
+ * **The pin is applied first, and the segment is chosen against the version it
165
+ * chose** (0383, *Audiences*). The rules sort the reader as they do now — they
166
+ * read the context, never the page — but the forms were authored against the
167
+ * version in `pages`, so a form that does not apply to the version a pinned
168
+ * reader was given is refused by the composition, and this answers that reader
169
+ * the version they were pinned to without their segment's form. That is the
170
+ * same trade `refusal` already describes one dimension across: the reader keeps
171
+ * their page, their signals say they were shown the base, and the deployment is
172
+ * told why.
173
+ */
174
+ export declare const pageForReader: (held: LivePages, built: LoomTree, context: JsonObject | undefined, pin?: number) => ServedPage;
175
+ /** Every live page held, in the order the door answered them. */
176
+ export declare const livePagesHeld: (held: LivePages) => readonly LoomTree[];
177
+ /**
178
+ * Whether the server is drawing on pages the door confirmed, rather than on
179
+ * nothing.
180
+ *
181
+ * A site holding pages after ten failed pulls is still serving Loom's pages,
182
+ * which is the behaviour clause 4 asks for and not a state worth hiding. What
183
+ * `failures` is for is saying so out loud in a log; what this is for is the
184
+ * simpler question of whether the door has ever been reached.
185
+ */
186
+ export declare const isPulling: (held: LivePages) => boolean;
187
+ //# sourceMappingURL=pages.d.ts.map
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The live pages a customer's server holds, and the one question a render asks
3
+ * of them.
4
+ *
5
+ * Loom is not in the render path (0262), so a page that an accepted change has
6
+ * moved cannot be fetched while a reader waits for it. What the server does
7
+ * instead is keep the project's live pages in its own process and draw from
8
+ * what it holds — and this is that holding, as a value rather than as a mutable
9
+ * cache. Every pull produces a new one; nothing here is edited in place, so a
10
+ * render that has already read a page cannot have it changed underneath.
11
+ *
12
+ * **A page this does not hold is not an error.** `livePageOf` answers
13
+ * `undefined`, and the caller renders the page as it was built. That is the
14
+ * whole of the fallback a host has to write, and it is the same answer for a
15
+ * server that has never pulled, a pull that failed, and a page the answer did
16
+ * not name.
17
+ */
18
+ import { composeTreeForContext, } from "../audience/compose.js";
19
+ import { ruleMatches } from "../audience/rule.js";
20
+ import { heldVersionFor, WINDOW_OFF } from "./window.js";
21
+ /**
22
+ * A server that has not pulled yet, which is every server at the moment it
23
+ * starts.
24
+ *
25
+ * It renders every page as built, so a deployment whose pull is misconfigured
26
+ * serves its site rather than an error — the property the pull exists to keep
27
+ * (0358 clause 4) is true before the first pull as well as after a failed one.
28
+ */
29
+ export const NO_LIVE_PAGES = {
30
+ pages: new Map(),
31
+ rules: new Map(),
32
+ forms: new Map(),
33
+ window: WINDOW_OFF,
34
+ tag: undefined,
35
+ pulledAt: undefined,
36
+ freshAt: undefined,
37
+ failures: 0,
38
+ };
39
+ /**
40
+ * The live page for this page id, or `undefined` to render the page as built.
41
+ *
42
+ * This is the only call a render path makes. Selection for an audience (0263)
43
+ * happens after it, in the customer's process, against the tree this answers —
44
+ * the pull carries no audience and the door refuses a request that names one.
45
+ *
46
+ * **With a reader's pin, the version they were pinned to** (0383 clause 2),
47
+ * which is the newest version of this page live at or before the pin. A pin the
48
+ * server cannot resolve, and a page it holds no earlier version of, read the
49
+ * newest live page; so does every reader of a project with no window, which is
50
+ * every project until one is chosen. `pinIn` reads the pin from the request's
51
+ * `Cookie` header and nothing about the reader goes any further than this call.
52
+ *
53
+ * The pin is an optional argument rather than a second function because the
54
+ * question is one question — *what do I draw for this reader* — and a host that
55
+ * honours a window should not have a second call to remember on each page.
56
+ */
57
+ export const livePageOf = (held, page, pin) => heldVersionFor(held.window, page, pin) ?? held.pages.get(page);
58
+ /**
59
+ * The segment this reader of this page is in, or `undefined` for none — which
60
+ * is `aud_everyone`, and is what a page with no rules answers for every reader.
61
+ *
62
+ * **Decided here, in the site's process, and never sent anywhere** (0262,
63
+ * 0371 clause 2). The context is whatever the host's server knows while it
64
+ * draws the page — `device`, `source`, `returning`, the keys its rules were
65
+ * written against — and none of it leaves this function: what comes out is a
66
+ * segment's name, which the host stamps on the page it renders so the page's
67
+ * signals are filed under it (0284).
68
+ *
69
+ * **One segment, the last rule that matches** (0385). A batch names one
70
+ * audience, so a reader two rules match is counted in one segment rather than
71
+ * in both, which would count one page view twice wherever segments are added
72
+ * up. The last rule is the one the portal orders general to specific, and the
73
+ * one that wins a contested part of the page (0359 clause 3), so it is the form
74
+ * the reader will be served once a segment has a form of its own.
75
+ *
76
+ * **This answers the name a signal is filed under, not the page that is
77
+ * served.** Which deltas a reader gets is `pageForReader`, and it is not the
78
+ * same question: a reader two rules match is in one segment for counting and
79
+ * is served both of their forms, in the deployment's order (0359 clause 3).
80
+ */
81
+ export const segmentOf = (held, page, context) => context === undefined
82
+ ? undefined
83
+ : (held.rules.get(page) ?? []).filter((rule) => ruleMatches(rule, context)).at(-1)?.audienceId;
84
+ /**
85
+ * The page and the rules a request composes from, with the rules narrowed to
86
+ * the segments that have a form.
87
+ *
88
+ * **A rule whose segment has no form is left out rather than refused.** A
89
+ * composition assembled by one writer treats a missing delta as a lost write,
90
+ * which is what `no-form` is for; a live pull assembles its overlay from two
91
+ * lists the door answers independently, and a segment that has rules and no
92
+ * form yet is the ordinary state of every segment made before anybody wrote
93
+ * one for it. Readers are still sorted into it (`segmentOf` reads every rule),
94
+ * and they are served the base — which is what they were served on the day the
95
+ * segment was named, and what pieces 1 to 3 of 0371 shipped.
96
+ */
97
+ const overlayFor = (rules, forms) => ({
98
+ rules: rules.filter((rule) => forms.some((form) => form.audienceId === rule.audienceId)),
99
+ forms,
100
+ });
101
+ /**
102
+ * What to render for this reader, and what to file their signals under.
103
+ *
104
+ * The one call a render path makes once a deployment has segments: it answers
105
+ * the live page composed with the forms this reader's segments earn, the
106
+ * segment's name for the page's signals, and — where the forms could not be
107
+ * applied — why.
108
+ *
109
+ * **A form that cannot be applied costs the reader their segment, not their
110
+ * page.** The two properties either side of this are both worth keeping and
111
+ * they pull apart exactly here. A pull that fails costs freshness and never the
112
+ * page (0358 clause 4), so there is always something to render. A composition
113
+ * refuses rather than falling back to the base (0263 clause 4), because a
114
+ * reader served the base whose page views are filed under `aud_eu` makes the
115
+ * comparison between two segments a comparison between one segment's form and
116
+ * another segment's *name over the base*.
117
+ *
118
+ * Dropping the audience keeps both: the reader gets the base page, their
119
+ * signals say what they were actually shown, and the deployment's figures stay
120
+ * a comparison of forms readers were served. The refusal is handed back rather
121
+ * than swallowed because a segment whose form has gone stale is a thing
122
+ * somebody must be told about — it is silent otherwise, and silently serving
123
+ * the base is the state 0263 clause 4 refuses.
124
+ *
125
+ * A deployment with no segments, a reader the rules do not match, and a server
126
+ * that has never pulled all answer the same way: the page, and no segment.
127
+ *
128
+ * **The pin is applied first, and the segment is chosen against the version it
129
+ * chose** (0383, *Audiences*). The rules sort the reader as they do now — they
130
+ * read the context, never the page — but the forms were authored against the
131
+ * version in `pages`, so a form that does not apply to the version a pinned
132
+ * reader was given is refused by the composition, and this answers that reader
133
+ * the version they were pinned to without their segment's form. That is the
134
+ * same trade `refusal` already describes one dimension across: the reader keeps
135
+ * their page, their signals say they were shown the base, and the deployment is
136
+ * told why.
137
+ */
138
+ export const pageForReader = (held, built, context, pin) => {
139
+ const base = livePageOf(held, built.treeId, pin) ?? built;
140
+ const audience = segmentOf(held, built.treeId, context);
141
+ const forms = held.forms.get(built.treeId) ?? [];
142
+ if (forms.length === 0)
143
+ return { tree: base, audience, refusal: undefined };
144
+ const composed = composeTreeForContext(base, overlayFor(held.rules.get(built.treeId) ?? [], forms), context);
145
+ return composed.ok
146
+ ? { tree: composed.value.tree, audience, refusal: undefined }
147
+ : { tree: base, audience: undefined, refusal: composed.error };
148
+ };
149
+ /** Every live page held, in the order the door answered them. */
150
+ export const livePagesHeld = (held) => [...held.pages.values()];
151
+ /**
152
+ * Whether the server is drawing on pages the door confirmed, rather than on
153
+ * nothing.
154
+ *
155
+ * A site holding pages after ten failed pulls is still serving Loom's pages,
156
+ * which is the behaviour clause 4 asks for and not a state worth hiding. What
157
+ * `failures` is for is saying so out loud in a log; what this is for is the
158
+ * simpler question of whether the door has ever been reached.
159
+ */
160
+ export const isPulling = (held) => held.pulledAt !== undefined;
161
+ //# sourceMappingURL=pages.js.map