iterate 0.3.0 → 0.4.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.
- package/README.md +164 -82
- package/dist/{next/api.d.ts → api.d.ts} +197 -33
- package/dist/{next/app-server.d.ts → app-server.d.ts} +7 -0
- package/dist/{next/app-server.mjs → app-server.mjs} +17 -15
- package/dist/app-server.mjs.map +1 -0
- package/dist/{next/app-session.mjs → app-session.mjs} +12 -15
- package/dist/app-session.mjs.map +1 -0
- package/dist/{next/app.mjs → app.mjs} +53 -14
- package/dist/app.mjs.map +1 -0
- package/dist/{next/client → client}/live-state.d.ts +11 -11
- package/dist/client/oauth.d.ts +17 -0
- package/dist/{next/client → client}/react.d.ts +10 -42
- package/dist/{next/client → client}/socket.d.ts +1 -0
- package/dist/client.mjs +156 -4
- package/dist/client.mjs.map +1 -0
- package/dist/{next/expression.d.ts → expression.d.ts} +11 -69
- package/dist/{next/expression.mjs → expression.mjs} +11 -109
- package/dist/expression.mjs.map +1 -0
- package/dist/lib-BWr-5mFO.mjs +36 -0
- package/dist/lib-BWr-5mFO.mjs.map +1 -0
- package/dist/{next/lib.d.ts → lib.d.ts} +16 -2
- package/dist/{next/lib.mjs → lib.mjs} +32 -3
- package/dist/lib.mjs.map +1 -0
- package/dist/node.d.ts +15 -3
- package/dist/node.mjs +36 -174
- package/dist/node.mjs.map +1 -1
- package/dist/{next/oauth-scopes.mjs → oauth-scopes.mjs} +1 -1
- package/dist/oauth-scopes.mjs.map +1 -0
- package/dist/{next/oauth.mjs → oauth.mjs} +14 -2
- package/dist/oauth.mjs.map +1 -0
- package/dist/principal.d.ts +8 -0
- package/dist/principal.mjs +8 -0
- package/dist/principal.mjs.map +1 -0
- package/dist/project-ingress.d.ts +58 -0
- package/dist/project-ingress.mjs +104 -0
- package/dist/project-ingress.mjs.map +1 -0
- package/dist/{next/react.mjs → react.mjs} +12 -12
- package/dist/react.mjs.map +1 -0
- package/dist/sdk/auth.d.ts +25 -0
- package/dist/sdk/index.d.ts +155 -0
- package/dist/sdk/record-pipelined-steps.d.ts +19 -0
- package/dist/sdk.mjs +245 -2
- package/dist/sdk.mjs.map +1 -0
- package/dist/{next/stream → stream}/processor.d.ts +28 -23
- package/dist/{next/stream → stream}/processor.mjs +48 -25
- package/dist/stream/processor.mjs.map +1 -0
- package/dist/{next/stream → stream}/run.d.ts +9 -6
- package/dist/{next/stream → stream}/run.mjs +13 -8
- package/dist/stream/run.mjs.map +1 -0
- package/dist/stream/test-support.d.ts +45 -0
- package/dist/stream/test-support.mjs +196 -0
- package/dist/stream/test-support.mjs.map +1 -0
- package/package.json +65 -219
- package/THIRD_PARTY_NOTICES.md +0 -55
- package/bin/iterate.js +0 -94
- package/dist/api-url-B6404M82.mjs +0 -17
- package/dist/api-url-B6404M82.mjs.map +0 -1
- package/dist/app-ref-BipL0feU.mjs +0 -35
- package/dist/app-ref-BipL0feU.mjs.map +0 -1
- package/dist/app-ref-C1CrgXqX.mjs +0 -7
- package/dist/app-ref-C1CrgXqX.mjs.map +0 -1
- package/dist/app-ref-DYai_om1.mjs +0 -7
- package/dist/app-ref-DYai_om1.mjs.map +0 -1
- package/dist/cli-D0c-pDL_.mjs +0 -1010
- package/dist/cli-D0c-pDL_.mjs.map +0 -1
- package/dist/client.d.ts +0 -3
- package/dist/cloudflare-BTm90gQ4.mjs +0 -951
- package/dist/cloudflare-BTm90gQ4.mjs.map +0 -1
- package/dist/contract-s4FW4eES.mjs +0 -309
- package/dist/contract-s4FW4eES.mjs.map +0 -1
- package/dist/document-review/index.d.ts +0 -5
- package/dist/document-review/types.d.ts +0 -107
- package/dist/document-review.mjs +0 -7015
- package/dist/document-review.mjs.map +0 -1
- package/dist/durable-object-processor-durability-CNsTjAJS.mjs +0 -205
- package/dist/durable-object-processor-durability-CNsTjAJS.mjs.map +0 -1
- package/dist/idempotency-DleloJNt.mjs +0 -28
- package/dist/idempotency-DleloJNt.mjs.map +0 -1
- package/dist/index.d.mts +0 -5
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/dist/itx/api-url.d.ts +0 -6
- package/dist/itx/itx-node-client.d.ts +0 -65
- package/dist/itx/itx-session.d.ts +0 -215
- package/dist/itx/owned-rpc-session.d.ts +0 -14
- package/dist/itx/query-client.d.ts +0 -10
- package/dist/itx-api.generated.d.ts +0 -6195
- package/dist/itx-session-sjud8GiT.mjs +0 -534
- package/dist/itx-session-sjud8GiT.mjs.map +0 -1
- package/dist/live-state-BJNqOwFw.mjs +0 -299
- package/dist/live-state-BJNqOwFw.mjs.map +0 -1
- package/dist/next/app-server.mjs.map +0 -1
- package/dist/next/app-session.mjs.map +0 -1
- package/dist/next/app.mjs.map +0 -1
- package/dist/next/client/oauth.d.ts +0 -12
- package/dist/next/client.mjs +0 -156
- package/dist/next/client.mjs.map +0 -1
- package/dist/next/expression.mjs.map +0 -1
- package/dist/next/lib.mjs.map +0 -1
- package/dist/next/oauth-scopes.mjs.map +0 -1
- package/dist/next/oauth.mjs.map +0 -1
- package/dist/next/principal.d.ts +0 -64
- package/dist/next/principal.mjs +0 -98
- package/dist/next/principal.mjs.map +0 -1
- package/dist/next/project-ingress.d.ts +0 -37
- package/dist/next/project-ingress.mjs +0 -75
- package/dist/next/project-ingress.mjs.map +0 -1
- package/dist/next/react.mjs.map +0 -1
- package/dist/next/sdk/auth.d.ts +0 -5
- package/dist/next/sdk/index.d.ts +0 -112
- package/dist/next/sdk.mjs +0 -139
- package/dist/next/sdk.mjs.map +0 -1
- package/dist/next/stream/processor.mjs.map +0 -1
- package/dist/next/stream/run.mjs.map +0 -1
- package/dist/next-node.d.ts +0 -15
- package/dist/next-node.mjs +0 -51
- package/dist/next-node.mjs.map +0 -1
- package/dist/processor-host-capabilities-BMFH3KTM.mjs +0 -56
- package/dist/processor-host-capabilities-BMFH3KTM.mjs.map +0 -1
- package/dist/processors/cloudflare.d.ts +0 -3
- package/dist/processors/durable-object-processor-durability.d.ts +0 -79
- package/dist/processors/event-consumption-metrics.d.ts +0 -82
- package/dist/processors/idempotency.d.ts +0 -13
- package/dist/processors/index.d.ts +0 -12
- package/dist/processors/processor-contracts.d.ts +0 -342
- package/dist/processors/processor-facet.d.ts +0 -186
- package/dist/processors/processor-host-capabilities.d.ts +0 -60
- package/dist/processors/prompt-sections.d.ts +0 -17
- package/dist/processors/rpc-types.d.ts +0 -515
- package/dist/processors/schemas.d.ts +0 -102
- package/dist/processors/stream-handle.d.ts +0 -45
- package/dist/processors/stream-processor-keepalive.d.ts +0 -95
- package/dist/processors/stream-processor-registry.d.ts +0 -233
- package/dist/processors/stream-processor-runner.d.ts +0 -289
- package/dist/processors/stream-processor.d.ts +0 -339
- package/dist/processors/stream-runtime-metrics.d.ts +0 -107
- package/dist/processors/testing.d.ts +0 -302
- package/dist/processors-BoNyeBfQ.mjs +0 -10
- package/dist/processors-BoNyeBfQ.mjs.map +0 -1
- package/dist/processors-cloudflare.mjs +0 -3
- package/dist/processors-testing.mjs +0 -435
- package/dist/processors-testing.mjs.map +0 -1
- package/dist/processors.mjs +0 -52
- package/dist/processors.mjs.map +0 -1
- package/dist/protocol-DnK_f2m6.mjs +0 -251
- package/dist/protocol-DnK_f2m6.mjs.map +0 -1
- package/dist/sdk/capnweb/index.d.ts +0 -2
- package/dist/sdk/capnweb/live-state/compact.d.ts +0 -5
- package/dist/sdk/capnweb/live-state/diff.d.ts +0 -41
- package/dist/sdk/capnweb/live-state/engine.d.ts +0 -44
- package/dist/sdk/capnweb/live-state/index.d.ts +0 -41
- package/dist/sdk/capnweb/live-state/protocol.d.ts +0 -87
- package/dist/sdk/capnweb/live-state/retain.d.ts +0 -23
- package/dist/sdk/capnweb/live-state/store.d.ts +0 -20
- package/dist/sdk/capnweb/live-state/types.d.ts +0 -11
- package/dist/sdk/capnweb/react.d.ts +0 -45
- package/dist/sdk/capnweb/react.mjs +0 -316
- package/dist/sdk/capnweb/react.mjs.map +0 -1
- package/dist/sdk/capnweb.mjs +0 -4
- package/dist/sdk/itx/react.d.ts +0 -191
- package/dist/sdk/itx/react.mjs +0 -383
- package/dist/sdk/itx/react.mjs.map +0 -1
- package/dist/sdk-DMB-IM11.mjs +0 -933
- package/dist/sdk-DMB-IM11.mjs.map +0 -1
- package/dist/sdk.d.ts +0 -339
- package/dist/serve-itx.d.ts +0 -46
- package/dist/starter-apps/flake-dashboard/app-ref.d.ts +0 -31
- package/dist/starter-apps/flake-dashboard/configured-worker.mjs +0 -1055
- package/dist/starter-apps/flake-dashboard/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/flake-dashboard/contract.d.ts +0 -4839
- package/dist/starter-apps/flake-dashboard/contract.mjs +0 -2
- package/dist/starter-apps/flake-dashboard/index.d.ts +0 -17
- package/dist/starter-apps/flake-dashboard/index.mjs +0 -56
- package/dist/starter-apps/flake-dashboard/index.mjs.map +0 -1
- package/dist/starter-apps/flake-dashboard/worker.d.ts +0 -4607
- package/dist/starter-apps/github-ai-linter/ai-linter.d.ts +0 -8914
- package/dist/starter-apps/github-ai-linter/configured-worker.mjs +0 -17987
- package/dist/starter-apps/github-ai-linter/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/github-ai-linter/contract.d.ts +0 -9193
- package/dist/starter-apps/github-ai-linter/index.d.ts +0 -10
- package/dist/starter-apps/github-ai-linter/index.mjs +0 -36
- package/dist/starter-apps/github-ai-linter/index.mjs.map +0 -1
- package/dist/starter-apps/github-ai-linter/prompt.d.ts +0 -13
- package/dist/starter-apps/github-ai-linter/review-bot.d.ts +0 -808
- package/dist/starter-apps/github-ai-linter/rules.d.ts +0 -34
- package/dist/starter-apps/github-ai-linter/worker-ref.d.ts +0 -19
- package/dist/starter-apps/github-ai-linter/worker.d.ts +0 -19
- package/dist/starter-apps/github-ai-linter/worker.mjs +0 -947
- package/dist/starter-apps/github-ai-linter/worker.mjs.map +0 -1
- package/dist/starter-apps/guestbook/app-ref.d.ts +0 -27
- package/dist/starter-apps/guestbook/client.d.ts +0 -7
- package/dist/starter-apps/guestbook/client.mjs +0 -59
- package/dist/starter-apps/guestbook/configured-worker.mjs +0 -205
- package/dist/starter-apps/guestbook/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/guestbook/index.d.ts +0 -9
- package/dist/starter-apps/guestbook/index.mjs +0 -31
- package/dist/starter-apps/guestbook/index.mjs.map +0 -1
- package/dist/starter-apps/guestbook/processor.d.ts +0 -2267
- package/dist/starter-apps/guestbook/worker.d.ts +0 -26
- package/dist/starter-apps/guestbook/worker.mjs +0 -191
- package/dist/starter-apps/guestbook/worker.mjs.map +0 -1
- package/dist/starter-apps/media/configured-worker.mjs +0 -577
- package/dist/starter-apps/media/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/media/index.mjs +0 -36
- package/dist/starter-apps/media/index.mjs.map +0 -1
- package/dist/starter-apps/media/ref.mjs +0 -20
- package/dist/starter-apps/media/ref.mjs.map +0 -1
- package/dist/starter-apps/media/worker.mjs +0 -579
- package/dist/starter-apps/media/worker.mjs.map +0 -1
- package/dist/starter-apps/notes/configured-worker.mjs +0 -6134
- package/dist/starter-apps/notes/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/notes/index.mjs +0 -23
- package/dist/starter-apps/notes/index.mjs.map +0 -1
- package/dist/starter-apps/notes/ref.mjs +0 -21
- package/dist/starter-apps/notes/ref.mjs.map +0 -1
- package/dist/starter-apps/notes/worker.mjs +0 -427
- package/dist/starter-apps/notes/worker.mjs.map +0 -1
- package/dist/starter-apps/todo/client.mjs +0 -59
- package/dist/starter-apps/todo/configured-worker.mjs +0 -2864
- package/dist/starter-apps/todo/configured-worker.mjs.map +0 -1
- package/dist/starter-apps/todo/index.d.ts +0 -8
- package/dist/starter-apps/todo/index.mjs +0 -29
- package/dist/starter-apps/todo/index.mjs.map +0 -1
- package/dist/stream-processor-keepalive-DAQTP6m3.mjs +0 -2082
- package/dist/stream-processor-keepalive-DAQTP6m3.mjs.map +0 -1
- package/dist/usingCtx-mZx5nsAW.mjs +0 -11800
- package/dist/usingCtx-mZx5nsAW.mjs.map +0 -1
- package/dist/worker-ref-DZxPDmb_.mjs +0 -390
- package/dist/worker-ref-DZxPDmb_.mjs.map +0 -1
- package/dist/worker.d.mts +0 -33
- package/dist/worker.mjs +0 -18
- package/dist/worker.mjs.map +0 -1
- package/menubar/Iterate.entitlements +0 -12
- package/menubar/Iterate.swift +0 -914
- package/menubar/IterateIcon.swift +0 -145
- package/menubar/README.md +0 -28
- package/menubar/build-menubar-app.sh +0 -59
- /package/dist/{next/api.mjs → api.mjs} +0 -0
- /package/dist/{next/app-session.d.ts → app-session.d.ts} +0 -0
- /package/dist/{next/app.d.ts → app.d.ts} +0 -0
- /package/dist/{next/oauth-scopes.d.ts → oauth-scopes.d.ts} +0 -0
package/dist/next/client.mjs
DELETED
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
import { applyPatch } from "./lib.mjs";
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
//#region src/next/client/live-state.ts
|
|
4
|
-
/** The delta as it arrives over the wire — PARSED, never cast: `from`/`to` MUST be real numbers (a
|
|
5
|
-
* non-numeric rev would poison the held revision and silently wedge every later frame), and each
|
|
6
|
-
* patch op is a known RFC-6902-subset shape. A frame that fails this heals through the seed door
|
|
7
|
-
* rather than being applied — the same recovery the store already runs on a revision gap. */
|
|
8
|
-
const LiveStateDeltaMessage = z.object({
|
|
9
|
-
key: z.string(),
|
|
10
|
-
from: z.number(),
|
|
11
|
-
to: z.number(),
|
|
12
|
-
patch: z.array(z.union([
|
|
13
|
-
z.object({
|
|
14
|
-
op: z.literal("add"),
|
|
15
|
-
path: z.string(),
|
|
16
|
-
value: z.unknown()
|
|
17
|
-
}),
|
|
18
|
-
z.object({
|
|
19
|
-
op: z.literal("replace"),
|
|
20
|
-
path: z.string(),
|
|
21
|
-
value: z.unknown()
|
|
22
|
-
}),
|
|
23
|
-
z.object({
|
|
24
|
-
op: z.literal("remove"),
|
|
25
|
-
path: z.string()
|
|
26
|
-
})
|
|
27
|
-
])).nullable()
|
|
28
|
-
});
|
|
29
|
-
function createLiveStateStore() {
|
|
30
|
-
let held = {
|
|
31
|
-
rev: null,
|
|
32
|
-
state: void 0
|
|
33
|
-
};
|
|
34
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
35
|
-
const notify = () => listeners.forEach((l) => l());
|
|
36
|
-
return {
|
|
37
|
-
get: () => held.state,
|
|
38
|
-
rev: () => held.rev,
|
|
39
|
-
subscribe: (listener) => {
|
|
40
|
-
listeners.add(listener);
|
|
41
|
-
return () => void listeners.delete(listener);
|
|
42
|
-
},
|
|
43
|
-
seed: (seed) => {
|
|
44
|
-
if (held.rev !== null && seed.rev < held.rev) return;
|
|
45
|
-
held = {
|
|
46
|
-
rev: seed.rev,
|
|
47
|
-
state: seed.state
|
|
48
|
-
};
|
|
49
|
-
notify();
|
|
50
|
-
},
|
|
51
|
-
apply: (delta, resync) => {
|
|
52
|
-
if (held.rev !== null && delta.to <= held.rev) return;
|
|
53
|
-
if (delta.from !== held.rev || !delta.patch) {
|
|
54
|
-
resync();
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
held = {
|
|
58
|
-
rev: delta.to,
|
|
59
|
-
state: applyPatch(held.state, delta.patch)
|
|
60
|
-
};
|
|
61
|
-
notify();
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
/** Subscribe to a producer's live state and reduce it into a store. `door` reads the seed
|
|
66
|
-
* (`itx.invoke("itx.facets.get('slug').liveSnapshot()")` for a processor, or a mini-app's
|
|
67
|
-
* own `state()` method). Subscribe happens BEFORE the first seed, so a delta racing the seed just
|
|
68
|
-
* triggers one door re-read — never a lost update. Gap heals are SINGLE-FLIGHT (a burst of gapped
|
|
69
|
-
* frames triggers one door read, not one per frame); a failed heal is reported through `onResync`
|
|
70
|
-
* and retried by the next delivered delta (its `from` still mismatches, so it re-triggers). */
|
|
71
|
-
async function connectLiveState(itx, opts) {
|
|
72
|
-
const store = createLiveStateStore();
|
|
73
|
-
let healing = false;
|
|
74
|
-
let healWantedAgain = false;
|
|
75
|
-
let disposed = false;
|
|
76
|
-
const reseed = () => {
|
|
77
|
-
if (disposed) return;
|
|
78
|
-
if (healing) {
|
|
79
|
-
healWantedAgain = true;
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
healing = true;
|
|
83
|
-
const settled = () => {
|
|
84
|
-
healing = false;
|
|
85
|
-
if (disposed || !healWantedAgain) return;
|
|
86
|
-
healWantedAgain = false;
|
|
87
|
-
reseed();
|
|
88
|
-
};
|
|
89
|
-
opts.door().then((s) => {
|
|
90
|
-
if (!disposed) {
|
|
91
|
-
store.seed(s);
|
|
92
|
-
opts.onResync?.("healed");
|
|
93
|
-
}
|
|
94
|
-
settled();
|
|
95
|
-
}, (e) => {
|
|
96
|
-
if (!disposed) opts.onResync?.(e instanceof Error ? e : new Error(String(e)));
|
|
97
|
-
settled();
|
|
98
|
-
});
|
|
99
|
-
};
|
|
100
|
-
const subscription = await itx.subscribe({
|
|
101
|
-
name: opts.name,
|
|
102
|
-
consumes: ["events.iterate.com/live-state/changed"],
|
|
103
|
-
target: (events) => {
|
|
104
|
-
if (disposed) return;
|
|
105
|
-
for (const e of events) {
|
|
106
|
-
let parsed;
|
|
107
|
-
try {
|
|
108
|
-
parsed = LiveStateDeltaMessage.safeParse(JSON.parse(JSON.stringify(e.payload)));
|
|
109
|
-
} catch {
|
|
110
|
-
parsed = void 0;
|
|
111
|
-
}
|
|
112
|
-
if (!parsed?.success) {
|
|
113
|
-
reseed();
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
if (parsed.data.key !== opts.key) continue;
|
|
117
|
-
try {
|
|
118
|
-
store.apply(parsed.data, reseed);
|
|
119
|
-
} catch {
|
|
120
|
-
reseed();
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
try {
|
|
126
|
-
const seed = opts.door();
|
|
127
|
-
const { signal } = opts;
|
|
128
|
-
const aborted = signal && new Promise((_, reject) => {
|
|
129
|
-
const abort = () => reject(signal.reason ?? /* @__PURE__ */ new Error("connectLiveState: aborted while the first seed was pending"));
|
|
130
|
-
if (signal.aborted) abort();
|
|
131
|
-
else signal.addEventListener("abort", abort, { once: true });
|
|
132
|
-
});
|
|
133
|
-
if (aborted) seed.catch(() => void 0);
|
|
134
|
-
store.seed(await (aborted ? Promise.race([seed, aborted]) : seed));
|
|
135
|
-
} catch (error) {
|
|
136
|
-
disposed = true;
|
|
137
|
-
try {
|
|
138
|
-
subscription[Symbol.dispose]();
|
|
139
|
-
} catch {}
|
|
140
|
-
throw error;
|
|
141
|
-
}
|
|
142
|
-
return {
|
|
143
|
-
store,
|
|
144
|
-
async dispose() {
|
|
145
|
-
if (disposed) return;
|
|
146
|
-
disposed = true;
|
|
147
|
-
try {
|
|
148
|
-
subscription[Symbol.dispose]();
|
|
149
|
-
} catch {}
|
|
150
|
-
}
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
//#endregion
|
|
154
|
-
export { connectLiveState, createLiveStateStore };
|
|
155
|
-
|
|
156
|
-
//# sourceMappingURL=client.mjs.map
|
package/dist/next/client.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../../src/next/client/live-state.ts"],"sourcesContent":["// client/live-state.ts — THE CLIENT HALF of live state (`iterate/next/client`), framework-free, for\n// browsers and node test clients. Two concepts:\n// live state store — `createLiveStateStore`: the pure reduce — seed through the door, apply each delta, heal on a gap\n// live state client — `connectLiveState`: wire an itx session's `subscribe` + a seed door to the store\n\nimport { z } from \"zod\";\nimport { applyPatch, type PatchOp } from \"../lib.ts\";\n\n// ── live state store ── THE CLIENT HALF of live state, for browsers and node test clients.\n// Adapted from apps/os's `createLiveStateStore` (packages/iterate/src/sdk/capnweb/live-state), kept\n// deliberately tiny, and pointed at the CLEAN-ROOM wire instead of apps/os's in-band snapshot:\n//\n// • SEED through the producer's door — `{rev, state}` read via an RPC method (a processor's\n// `liveSnapshot()`, a mini-app's `state()`). apps/os reduces the first snapshot in-band on the\n// subscription; here the stream keeps no per-subscriber state, so the seed is a separate read.\n// • APPLY each `{key, from, to, patch}` delta the subscription delivers: a patch lands only when\n// its `from` matches the held rev; a mismatch means a missed delta (or a reborn producer's fresh\n// epoch) — resync by re-reading the door, exactly like apps/os's revision-gap resync.\n//\n// The patch format is lib.ts (an RFC-6902 subset), so this store shares ONE applyPatch with\n// the producer — no second diff implementation. No capnweb import: a caller wires the transport and\n// hands deltas in, so the same store backs a node test client and the React hook (client/demo.tsx).\n\n/** One live-state delta off the wire — the payload of an `events.iterate.com/live-state/changed`\n * ephemeral event, delivered raw to the subscriber. */\n/** `patch: null` = the change was too large to send — the rev moved, re-seed through the door. */\nexport type LiveStateDelta = { key: string; from: number; to: number; patch: PatchOp[] | null };\n\n/** The delta as it arrives over the wire — PARSED, never cast: `from`/`to` MUST be real numbers (a\n * non-numeric rev would poison the held revision and silently wedge every later frame), and each\n * patch op is a known RFC-6902-subset shape. A frame that fails this heals through the seed door\n * rather than being applied — the same recovery the store already runs on a revision gap. */\nconst LiveStateDeltaMessage: z.ZodType<LiveStateDelta> = z.object({\n key: z.string(),\n from: z.number(),\n to: z.number(),\n patch: z\n .array(\n z.union([\n z.object({ op: z.literal(\"add\"), path: z.string(), value: z.unknown() }),\n z.object({ op: z.literal(\"replace\"), path: z.string(), value: z.unknown() }),\n z.object({ op: z.literal(\"remove\"), path: z.string() }),\n ]),\n )\n .nullable(),\n});\n\n/** What the producer's seed door returns: the current revision paired with the current value. */\nexport type LiveStateSeed<S> = { rev: number; state: S };\n\nexport type LiveStateStore<S> = {\n /** The current value, or undefined until the first seed lands. */\n get(): S | undefined;\n /** The held revision, or null before the first seed. */\n rev(): number | null;\n /** Subscribe to changes (for React's useSyncExternalStore, or a test's await-loop). */\n subscribe(listener: () => void): () => void;\n /** Seed (or re-seed) from the door — the first paint, and the heal after a gap. */\n seed(seed: LiveStateSeed<S>): void;\n /** Reduce one delta in; on a revision gap call `resync` and hold the value until a fresh seed. */\n apply(delta: LiveStateDelta, resync: () => void): void;\n};\n\nexport function createLiveStateStore<S>(): LiveStateStore<S> {\n // `rev: null` until the first seed lands.\n let held: { rev: number | null; state: S | undefined } = { rev: null, state: undefined };\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((l) => l());\n return {\n get: () => held.state,\n rev: () => held.rev,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n seed: (seed) => {\n // MONOTONIC: a late-resolving OLDER door read must never move the store backwards past state\n // deltas have already advanced (a delta-triggered resync can race the initial seed). Revisions\n // are time-seeded epochs plus increments, so \"newer\" is numeric.\n if (held.rev !== null && seed.rev < held.rev) return;\n held = { rev: seed.rev, state: seed.state };\n notify();\n },\n apply: (delta, resync) => {\n // A delta at-or-behind the held rev is a duplicate/out-of-order frame — drop it silently.\n // (Epochs are minted from the clock, so a reborn producer's fresh chain sits numerically above\n // every rev an old chain handed out; a frame wholly behind us is genuinely old. The one\n // exception is a clock that regressed across a producer rebirth — accepted: the next applied\n // or gapped frame resyncs through the door anyway.)\n if (held.rev !== null && delta.to <= held.rev) return;\n // A gap (its `from` is not the held rev — including \"no seed yet\") means a missed delta or a\n // reborn epoch, and a `null` patch means the change was too large to send — either way re-read\n // the door instead of applying onto a diverged base.\n if (delta.from !== held.rev || !delta.patch) {\n resync();\n return;\n }\n held = { rev: delta.to, state: applyPatch(held.state as S, delta.patch) };\n notify();\n },\n };\n}\n\n// ── live state client ── wire an itx session's `subscribe` + a seed door to a LiveStateStore.\n// This is the whole cleanroom client: a subscription that consumes the one live-state event type\n// (`itx.subscribe({ target, consumes: [\"events.iterate.com/live-state/changed\"] })`) delivers every\n// key's deltas in batches; this filters the watched `key` and reduces each delta into the store; a\n// `door` thunk reads `{rev, state}` for the first paint and every gap heal. Transport lives here so\n// the store (client/live-state.ts) and the React hook stay pure.\n\n/** The slice of an itx session this needs — a capnweb `IterateContextRpcTarget` proxy satisfies it structurally:\n * `subscribe` hands back a DISPOSABLE handle (disposing it removes the subscription server-side). */\nexport type LiveStateItx = {\n subscribe(input: {\n name?: string;\n consumes?: string[];\n target: (events: unknown[], range: unknown) => void;\n }): Promise<{ [Symbol.dispose](): void }>;\n};\n\n/** A connected live-state subscription: the store rendering it, and the dispose that removes the\n * server-side subscription (the handle's disposer; the session's end does the same). */\nexport type LiveStateConnection<S> = {\n store: LiveStateStore<S>;\n /** Unsubscribe on the server and stop reducing deltas. Safe to call more than once. */\n dispose(): Promise<void>;\n};\n\n/** Subscribe to a producer's live state and reduce it into a store. `door` reads the seed\n * (`itx.invoke(\"itx.facets.get('slug').liveSnapshot()\")` for a processor, or a mini-app's\n * own `state()` method). Subscribe happens BEFORE the first seed, so a delta racing the seed just\n * triggers one door re-read — never a lost update. Gap heals are SINGLE-FLIGHT (a burst of gapped\n * frames triggers one door read, not one per frame); a failed heal is reported through `onResync`\n * and retried by the next delivered delta (its `from` still mismatches, so it re-triggers). */\nexport async function connectLiveState<S>(\n itx: LiveStateItx,\n opts: {\n key: string;\n name?: string;\n door: () => Promise<LiveStateSeed<S>>;\n /** Called after each gap heal attempt: \"healed\" on a fresh seed, the error when the door read\n * failed (the store keeps its last value; the next delta retries). */\n onResync?: (result: \"healed\" | Error) => void;\n /** Abort while the FIRST seed is still pending (a component unmounting): the row just configured\n * is recalled and the connect rejects — a door that never answers leaves nothing lent. */\n signal?: AbortSignal;\n },\n): Promise<LiveStateConnection<S>> {\n const store = createLiveStateStore<S>();\n let healing = false;\n let healWantedAgain = false; // a gap seen WHILE a heal was in flight: the seed may predate it\n let disposed = false;\n const reseed = () => {\n if (disposed) return;\n if (healing) {\n healWantedAgain = true;\n return;\n }\n healing = true;\n const settled = () => {\n healing = false;\n if (disposed || !healWantedAgain) return;\n healWantedAgain = false;\n reseed();\n };\n void opts.door().then(\n (s) => {\n if (!disposed) {\n store.seed(s);\n opts.onResync?.(\"healed\");\n }\n settled();\n },\n (e: unknown) => {\n if (!disposed) opts.onResync?.(e instanceof Error ? e : new Error(String(e)));\n settled();\n },\n );\n };\n const subscription = await itx.subscribe({\n name: opts.name,\n consumes: [\"events.iterate.com/live-state/changed\"],\n // A batch of live-state deltas (every key's); keep the watched key's. capnweb hands each event\n // as a live proxy value — deep-copy to a plain object before reducing.\n target: (events: unknown[]) => {\n if (disposed) return;\n for (const e of events) {\n // capnweb hands each event as a live proxy value — deep-copy to a plain object, then PARSE\n // the frame (never cast network data). The whole decode is guarded: an ABSENT payload makes\n // `JSON.parse(JSON.stringify(undefined))` throw before validation, and any throw here would\n // skip every later delta in the batch. A malformed OR undecodable frame heals via the door\n // instead of poisoning the held rev or escaping this callback.\n let parsed: ReturnType<(typeof LiveStateDeltaMessage)[\"safeParse\"]> | undefined;\n try {\n parsed = LiveStateDeltaMessage.safeParse(\n JSON.parse(JSON.stringify((e as { payload: unknown }).payload)),\n );\n } catch {\n parsed = undefined;\n }\n if (!parsed?.success) {\n reseed();\n continue;\n }\n if (parsed.data.key !== opts.key) continue;\n // `store.apply` runs `applyPatch`, which THROWS on a patch it refuses (a `/__proto__` path a\n // legitimate state with an own `__proto__` key produces, say). Contain it per frame: heal via\n // the door — which re-seeds the state DIRECTLY, no patch to reject — instead of escaping this\n // callback and skipping every later frame.\n try {\n store.apply(parsed.data, reseed);\n } catch {\n reseed();\n }\n }\n },\n });\n try {\n const seed = opts.door();\n const { signal } = opts;\n const aborted =\n signal &&\n new Promise<never>((_, reject) => {\n const abort = () =>\n reject(\n signal.reason ??\n new Error(\"connectLiveState: aborted while the first seed was pending\"),\n );\n if (signal.aborted) abort();\n else signal.addEventListener(\"abort\", abort, { once: true });\n });\n if (aborted) seed.catch(() => undefined); // the door may still settle after the abort — quietly\n store.seed(await (aborted ? Promise.race([seed, aborted]) : seed));\n } catch (error) {\n // The seed failed after the row was configured: recall it, or the server keeps delivering to a\n // callback no one holds (and the session's other rows wait behind it).\n disposed = true;\n try {\n subscription[Symbol.dispose]();\n } catch {\n // a dead session has already removed it\n }\n throw error;\n }\n return {\n store,\n async dispose() {\n if (disposed) return;\n disposed = true;\n try {\n subscription[Symbol.dispose](); // the server removes the row and recalls the lent callback\n } catch {\n // a dead session has already removed it — the socket close disposed every handle\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,wBAAmD,EAAE,OAAO;CAChE,KAAK,EAAE,OAAO;CACd,MAAM,EAAE,OAAO;CACf,IAAI,EAAE,OAAO;CACb,OAAO,EACJ,MACC,EAAE,MAAM;EACN,EAAE,OAAO;GAAE,IAAI,EAAE,QAAQ,KAAK;GAAG,MAAM,EAAE,OAAO;GAAG,OAAO,EAAE,QAAQ;EAAE,CAAC;EACvE,EAAE,OAAO;GAAE,IAAI,EAAE,QAAQ,SAAS;GAAG,MAAM,EAAE,OAAO;GAAG,OAAO,EAAE,QAAQ;EAAE,CAAC;EAC3E,EAAE,OAAO;GAAE,IAAI,EAAE,QAAQ,QAAQ;GAAG,MAAM,EAAE,OAAO;EAAE,CAAC;CACxD,CAAC,CACH,CAAC,CACA,SAAS;AACd,CAAC;AAkBD,SAAgB,uBAA6C;CAE3D,IAAI,OAAqD;EAAE,KAAK;EAAM,OAAO,KAAA;CAAU;CACvF,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAe,UAAU,SAAS,MAAM,EAAE,CAAC;CACjD,OAAO;EACL,WAAW,KAAK;EAChB,WAAW,KAAK;EAChB,YAAY,aAAa;GACvB,UAAU,IAAI,QAAQ;GACtB,aAAa,KAAK,UAAU,OAAO,QAAQ;EAC7C;EACA,OAAO,SAAS;GAId,IAAI,KAAK,QAAQ,QAAQ,KAAK,MAAM,KAAK,KAAK;GAC9C,OAAO;IAAE,KAAK,KAAK;IAAK,OAAO,KAAK;GAAM;GAC1C,OAAO;EACT;EACA,QAAQ,OAAO,WAAW;GAMxB,IAAI,KAAK,QAAQ,QAAQ,MAAM,MAAM,KAAK,KAAK;GAI/C,IAAI,MAAM,SAAS,KAAK,OAAO,CAAC,MAAM,OAAO;IAC3C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,MAAM,UACJ,UACA,IAAI,SAAgB,GAAG,WAAW;GAChC,MAAM,cACJ,OACE,OAAO,0BACL,IAAI,MAAM,4DAA4D,CAC1E;GACF,IAAI,OAAO,SAAS,MAAM;QACrB,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EAC7D,CAAC;EACH,IAAI,SAAS,KAAK,YAAY,KAAA,CAAS;EACvC,MAAM,KAAK,OAAO,UAAU,QAAQ,KAAK,CAAC,MAAM,OAAO,CAAC,IAAI,KAAK;CACnE,SAAS,OAAO;EAGd,WAAW;EACX,IAAI;GACF,aAAa,OAAO,QAAQ,CAAC;EAC/B,QAAQ,CAER;EACA,MAAM;CACR;CACA,OAAO;EACL;EACA,MAAM,UAAU;GACd,IAAI,UAAU;GACd,WAAW;GACX,IAAI;IACF,aAAa,OAAO,QAAQ,CAAC;GAC/B,QAAQ,CAER;EACF;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"expression.mjs","names":["#dispatchItxExpressionSteps"],"sources":["../../src/next/expression.ts"],"sourcesContent":["// context/expression.ts — THE expression codec: the STRING half (itx.facets.get(\"core\")) ⇄ the\n// STRUCTURED half ([\"itx\", \"facets\", [\"get\", \"core\"]]). Args are ONE JSON5 grammar, comments included\n// (no hand-rolled number/object parser; __proto__-safe); expressions are persisted NAMES, so deleting\n// one IS revocation. The rewrite rules (match, rank, rewrite) are ./itx-expression-rewriting.ts. Two more concepts\n// ride with the codec, the only platform primitives the library tier may import:\n// dispatch — `walkSteps` / `callOn`: EXECUTE a rewritten call's steps against a live object graph\n// invoke handle — `InvokeHandle` + the prototype hop: the DOTTED DOOR, every unknown chain one `invoke(expression)`\nimport JSON5 from \"json5\";\nimport { RpcTarget } from \"capnweb\";\nimport { codedError, jsonEqual } from \"./lib.ts\";\n\n/** A STRING expression is for what a person types: short. Anything bigger — a worker's source, a large\n * literal — rides the PARSED form (`[\"itx\",\"workers\",[\"get\",{ source }]]`), which is plain data and never\n * meets json5. The cap is O(1), before any parsing (stock json5 allocates per character and a\n * multi-megabyte literal kills a 128 MiB isolate — the 2026-09-07 wave-0 plan, issue 2). */\nconst ITX_EXPRESSION_STRING_MAX_CHARS = 2048;\n\n/** One step: a property read (string) or a call (`[method, ...args]`). Args are plain JSON. The\n * method `\"\"` is the ANONYMOUS call — call the value itself: `itx.builtins.rpcStubs.get('cam')(1, 2)`\n * is `[\"itx\",\"builtins\",\"rpcStubs\",[\"get\",\"cam\"],[\"\",1,2]]` — what a `provide(stub)` rule spells when\n * the lent stub is called with args. */\nexport type ItxExpressionStep = string | [method: string, ...args: unknown[]];\n/** An itx expression as data: the scope root (`itx`) then get/call steps. THE parsed form every door\n * works on. */\nexport type ItxExpression = ItxExpressionStep[];\n/** THE dispatch target, in EITHER codec half — a dotted string that starts with the scope root\n * (`\"itx.facets.get('core')\"`) OR the parsed structured form (`[\"itx\",\"facets\",[\"get\",\"core\"]]`).\n * Both carry call args (the string via `.method(args)`), and `normalizedItxExpression` normalizes\n * either to the structured form — so either works wherever one works, at every door that dispatches. */\nexport type ItxExpressionInput = string | ItxExpression;\n/** An itx-expression PREFIX — a rewrite rule's `match`: dotted names, any of which may be a call step\n * PINNING literal args — `itx.ai.run` or `itx.ai.run('gpt-5')` or `itx.repo.get('main').files`. A\n * pinned arg must equal the call's arg at that position for the rule to match, and is CONSUMED by\n * the match (partial application): `itx.ai.run('gpt-5') ⇒ itx.openai.chat` makes\n * `itx.ai.run('gpt-5', inputs)` into `itx.openai.chat(inputs)`. */\nexport type ItxExpressionPrefix = ItxExpression;\n/** The name a step carries: the property itself, or a call step's method. */\nexport const itxExpressionStepName = (step: ItxExpressionStep | undefined): string | undefined =>\n Array.isArray(step) ? step[0] : step;\n\nconst IDENT = /^[A-Za-z_$][A-Za-z0-9_$-]*/;\nconst RESERVED = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n// ── `@`, THE CALLER'S INPUT — a rewrite rule's target may hold it, nothing else may ──\n// In the string half a bare `@` outside a string literal is the marker (`'@cf/…'` inside quotes is a\n// string like any other); `...@` as an object-literal entry is the merge form. In the array half the\n// marker is ONE reserved literal, `{ \"@\": true }`, and the merge entry the key `\"...@\"` with the value\n// `true` — so the stored form is plain JSON, and those two spellings are unspellable as literals in a\n// target (the codec's one reservation). What `@` MEANS is rule 7 in ./itx-expression-rewriting.ts; here\n// it is only lexed (parse, targets only) and printed back (print, targets only).\n/** The marker's array-half spelling, the one reserved literal. */\nconst ITX_EXPRESSION_HOLE = { \"@\": true } as const;\n/** The merge entry's key — `...@` — read by rule 7. */\nexport const ITX_EXPRESSION_MERGE_KEY = \"...@\";\n\n/** A single- or double-quoted string literal (escapes honored) or a JSON5 comment (block or line):\n * THE one pattern every walk that must skip what is inside them is built from — the marker lex, the\n * marker print, the paren matcher. In an alternation a span is consumed whole, so nothing inside one\n * (a quote in a comment, an `@` in a string) is ever seen by the other alternatives. */\nconst STRING_OR_COMMENT = String.raw`\"(?:[^\"\\\\]|\\\\[\\s\\S])*\"|'(?:[^'\\\\]|\\\\[\\s\\S])*'|/\\*[\\s\\S]*?\\*/|//[^\\n]*`;\nconst isStringOrComment = (match: string): boolean =>\n match[0] === '\"' || match[0] === \"'\" || match[0] === \"/\";\n/** In call args: a literal (kept verbatim) or a marker — `...@` before `@`, so the merge form wins. */\nconst MARKERS_IN_ARGS = new RegExp(`${STRING_OR_COMMENT}|\\\\.\\\\.\\\\.@|@`, \"g\");\n/** In JSON5's printed output: the marker literal `{'@':true}` and the merge entry `'...@':true` are\n * spelled with a single-quoted key and matched on those exact boundaries — listed BEFORE the literal\n * alternative so the entry's `'...@'` is read as the entry, not as a string. A user's string that\n * merely contains those characters is emitted by JSON5 as a longer (double-quoted) literal and is\n * consumed whole. */\nconst MARKERS_IN_PRINT = new RegExp(`\\\\{'@':true\\\\}|'\\\\.\\\\.\\\\.@':true|${STRING_OR_COMMENT}`, \"g\");\n/** A bracket outside a literal. */\nconst BRACKETS = new RegExp(`${STRING_OR_COMMENT}|[()[\\\\]{}]`, \"g\");\n\n/** Is `value` the marker literal `{ \"@\": true }`? */\nexport const isItxExpressionHole = (value: unknown): boolean =>\n jsonEqual(value, ITX_EXPRESSION_HOLE);\n\n/** Does `value` (a step, an arg tree, a whole expression) hold the marker or a merge entry anywhere? */\nexport function containsItxExpressionHole(value: unknown): boolean {\n if (isItxExpressionHole(value)) return true;\n if (Array.isArray(value)) return value.some(containsItxExpressionHole);\n // oxlint-disable-next-line iterate/simple-truthiness-check -- `value` is `unknown`; the typeof separates real objects from primitives (a bare truthiness check would recurse into strings/numbers)\n if (value !== null && typeof value === \"object\")\n return (\n (value as Record<string, unknown>)[ITX_EXPRESSION_MERGE_KEY] === true ||\n Object.values(value).some(containsItxExpressionHole)\n );\n return false;\n}\n\n/** Index of the `)` closing the `(` at `open`; tracks bracket depth, skipping quoted string args. */\nfunction matchingParen(source: string, open: number): number {\n let depth = 0;\n BRACKETS.lastIndex = open;\n for (let bracket = BRACKETS.exec(source); bracket; bracket = BRACKETS.exec(source)) {\n if (isStringOrComment(bracket[0])) continue;\n if (\"([{\".includes(bracket[0])) depth++;\n else if (--depth === 0) return bracket.index;\n }\n throw new Error(`expression: unbalanced \"(\" in ${JSON.stringify(source)}`);\n}\n\n/** Parse the STRING half: dotted names + `.method(args)` calls (args JSON5-parsed); rejects reserved\n * names + bare scope calls. `holes: true` — a rewrite rule's TARGET only — lexes `@` / `...@` into\n * the marker literals; anywhere else a bare `@` is refused. */\nexport function parse(source: string, options?: { holes?: boolean }): ItxExpression {\n if (source.length > ITX_EXPRESSION_STRING_MAX_CHARS)\n throw codedError(\n \"EXPRESSION_TOO_LONG\",\n `itx expression: ${source.length} chars is over the ${ITX_EXPRESSION_STRING_MAX_CHARS}-char limit for the string form — a string expression is for what a person types; pass the parsed form instead: [\"itx\",\"workers\",[\"get\",{ source: … }]]`,\n );\n const s = source.trim();\n const steps: ItxExpression = [];\n let i = 0;\n function fail(m: string): never {\n throw new Error(`expression: ${m} in ${JSON.stringify(source)}`); // decl, not arrow: TS never-narrows\n }\n const readName = (): string => {\n const m = IDENT.exec(s.slice(i));\n if (!m) fail(`name expected at ${i}`);\n if (RESERVED.has(m[0])) fail(`reserved name \"${m[0]}\"`);\n i += m[0].length;\n return m[0];\n };\n steps.push(readName()); // the scope root (itx)\n while (i < s.length) {\n const c = s[i];\n if (/\\s/.test(c)) i++;\n else if (c === \".\") steps.push((i++, readName()));\n else if (c === \"(\") {\n const end = matchingParen(s, i);\n const raw = s.slice(i + 1, end).trim();\n // `@` outside a string literal: the marker (targets only), a refusal everywhere else.\n const inner = raw.replace(MARKERS_IN_ARGS, (match) => {\n if (isStringOrComment(match)) return match;\n if (!options?.holes)\n fail(\"`@` (the caller's input) is legal only in a rewrite rule's target\");\n return match === \"@\"\n ? JSON.stringify(ITX_EXPRESSION_HOLE)\n : `${JSON.stringify(ITX_EXPRESSION_MERGE_KEY)}:true`;\n });\n let args: unknown[] = [];\n try {\n if (inner !== \"\") args = JSON5.parse(`[${inner}]`) as unknown[];\n } catch (e) {\n fail(`call args are not JSON5 (${(e as Error).message})`);\n }\n const previous = steps.at(-1);\n if (Array.isArray(previous))\n steps.push([\"\", ...args]); // `f(x)(y)`: call the result itself\n else {\n const name = steps.pop();\n if (typeof name !== \"string\") fail(\"a call must follow a name\");\n if (steps.length === 0) fail(\"cannot call the scope symbol itself\");\n steps.push([name, ...args]);\n }\n i = end + 1;\n } else fail(`unexpected ${JSON.stringify(c)} at ${i}`);\n }\n return steps;\n}\n\n/** The array half, checked the way the parser checks the string half — every name step an identifier\n * that is not reserved, every call step `[method, ...args]` with an identifier method (or `\"\"`, the\n * anonymous call, only right after a call) — WITHOUT printing and re-parsing: a stored target carries a worker's whole source as\n * data, and that data must never meet the string codec (the 2 KiB cap, json5). Throws in the\n * parser's words. */\nfunction assertItxExpressionShape(expression: ItxExpression): void {\n const fail = (m: string): never => {\n throw new Error(`expression: ${m} in ${JSON.stringify(expression).slice(0, 200)}`);\n };\n // oxlint-disable-next-line iterate/simple-truthiness-check -- runtime shape validation of wire/stored data; the ItxExpression array type is a claim here, not a guarantee\n if (!Array.isArray(expression) || expression.length === 0)\n fail(\"an expression is a non-empty array\");\n const name = (step: string, what: string) => {\n if (!IDENT.test(step) || IDENT.exec(step)![0] !== step)\n fail(`${what} ${JSON.stringify(step)} is not an identifier`);\n if (RESERVED.has(step)) fail(`reserved name \"${step}\"`);\n };\n expression.forEach((step, i) => {\n if (typeof step === \"string\") {\n name(step, i === 0 ? \"the root\" : \"a name step\");\n return;\n }\n // oxlint-disable-next-line iterate/simple-truthiness-check -- runtime shape validation of wire/stored data; the step's static array type is a claim here, not a guarantee\n if (!Array.isArray(step) || typeof step[0] !== \"string\")\n fail(`step ${i} is neither a name nor [method, ...args]`);\n const [method] = step;\n if (method === \"\") {\n if (i === 0 || !Array.isArray(expression[i - 1]))\n fail(\"the anonymous call `f(x)(y)` follows a call\");\n } else name(method, \"a method\");\n if (i === 0) fail(\"a call on the root itself\");\n });\n // No hole check on the array half: `{ \"@\": true }` carried as DATA is data (edge#6) — only the\n // STRING form lexes a bare `@` into the marker, and only for a rule's target.\n}\n\n/** THE ONE NORMALIZING DOOR: either half, normalized to the array half and checked — a string is\n * parsed (short by rule), an array is shape-checked in place. Every door that takes an\n * `ItxExpressionInput` (the edge `invoke`, the resolver, the event builders, the prefix parser\n * below) enters through it. */\nexport function normalizedItxExpression(\n input: ItxExpressionInput,\n options?: { holes?: boolean },\n): ItxExpression {\n if (typeof input === \"string\") return parse(input, options);\n assertItxExpressionShape(input);\n return input;\n}\n\n/** Object args print with their keys SORTED, so two spellings of one object are one canonical string\n * — one rewrite-rule row, one facet memo, one library connection memo (library.ts) — the way\n * `jsonEqual` already matches them. A `JSON.stringify` / `JSON5.stringify` replacer. */\nexport const keySortedForPrint = (_key: string, value: unknown): unknown =>\n // oxlint-disable-next-line iterate/simple-truthiness-check -- `value` is `unknown` (a JSON replacer arg); the typeof discriminates real objects from primitive values\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? Object.fromEntries(\n Object.keys(value as Record<string, unknown>)\n .sort()\n .map((k) => [k, (value as Record<string, unknown>)[k]]),\n )\n : value;\n\n/** Canonical stored form: dotted path + `.method(args)` calls (args `JSON5.stringify`d, object keys\n * sorted). `holes: true` — a rewrite rule's TARGET only — spells the marker literals back as `@` /\n * `...@`, and `parse(print(e, { holes: true }), { holes: true })` round-trips; without it the\n * reserved literals print as the plain JSON5 they are, so a CALL that happens to carry `{ \"@\": true }`\n * as data round-trips through `parse` (no holes) unchanged — the resolve/invoke law holds for it. */\nexport function print(expr: ItxExpression, options?: { holes?: boolean }): string {\n return expr\n .map((step, i) => {\n const dot = i ? \".\" : \"\";\n if (typeof step === \"string\") return dot + step;\n const json = JSON5.stringify(step.slice(1), keySortedForPrint).slice(1, -1);\n const args = options?.holes\n ? json.replace(MARKERS_IN_PRINT, (match) =>\n match === \"{'@':true}\" ? \"@\" : match === \"'...@':true\" ? \"...@\" : match,\n )\n : json;\n return step[0] === \"\" ? `(${args})` : `${dot}${step[0]}(${args})`;\n })\n .join(\"\");\n}\n\n/** Parse an itx-expression prefix (either codec half) — `normalizedItxExpression` (so every step is\n * an identifier that is not reserved, in either half) plus the two refusals only a PREFIX has: the\n * anonymous call step (`f(x)(y)` — a prefix cannot call a result), and a call step with NO args,\n * which pins nothing and is the same prefix as the plain name: spell `itx.ai.run`. */\nexport function parseItxExpressionPrefix(source: ItxExpressionInput): ItxExpressionPrefix {\n const expr = normalizedItxExpression(source);\n const spelled = typeof source === \"string\" ? source : print(expr);\n for (const step of expr) {\n if (!Array.isArray(step)) continue;\n if (step[0] === \"\")\n throw new Error(`an itx-expression prefix cannot call a result — ${JSON.stringify(spelled)}`);\n if (step.length === 1)\n throw new Error(\n `an itx-expression prefix pins literal args with a call step — ${JSON.stringify(spelled)} has \"${step[0]}()\" with none; spell \"${step[0]}\"`,\n );\n }\n return expr;\n}\n\n/** THE ONE canonical spelling of an itx-expression prefix — the rewrite-rule table's key, what a lent\n * stub is keyed by through `provide`'s sugar: parsed, then printed (dotted names; pinned args as JSON5\n * literals). */\nexport function canonicalItxExpressionPrefix(source: ItxExpressionInput): string {\n return print(parseItxExpressionPrefix(source));\n}\n\n// ── dispatch ── EXECUTE a rewritten call's steps against a LIVE object graph (the codec that\n// turns strings ⇄ these structures is above; the rules that rewrite a call to a built-in\n// root are ./itx-expression-rewriting.ts). `walkSteps` is THE step walk — `ItxExpressionResolver`\n// replays the steps after the root with it; the facet door and the delivery loop walk steps on a\n// local object with it. `callOn` applies args to a resolved value. The dotted write-half (a handle\n// whose dotted access reduces into one dispatch) is `InvokeHandle` (the next section) — the\n// ONE such primitive, pipelinable over Workers RPC.\n\n// Promise brands the step walk threads UNAWAITED: property access and calls pipeline on them\n// natively, so the whole chain reduces into one round trip and the caller's terminal await is the\n// single flush. os-next iterate-context.ts registers the native cloudflare:workers brands and capnweb's at boot — that\n// import can't live here because the unit lane runs this module in Node, where the list stays empty\n// and every step is simply awaited.\nconst PIPELINED_RPC_BRANDS: (abstract new (...args: never[]) => unknown)[] = [];\n/** Register a pipelinable promise brand (the workerd entrypoint's two calls at boot). */\nexport function registerPipelinedRpcBrand(brand: abstract new (...args: never[]) => unknown): void {\n PIPELINED_RPC_BRANDS.push(brand);\n}\nconst pipelined = (v: unknown): boolean => PIPELINED_RPC_BRANDS.some((b) => v instanceof b);\n\n/** Resolve one step's property. `__proto__` / `constructor` / `prototype` never resolve — `constructor`\n * would hand out the class itself (trusted clients or not, that is not a step anyone means). */\nfunction stepGet(value: object, key: string): unknown {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return undefined;\n return Reflect.get(value, key);\n}\n\n/**\n * THE step walk: property steps `Reflect.get` with the receiver carried; call steps `Reflect.apply`\n * ON that receiver (detaching a method from a Workers-RPC receiver breaks it); an ordinary promise\n * is awaited between steps, a branded one (PIPELINED_RPC_BRANDS, above) is not.\n *\n * ⚠️ DataCloneError LEARNING:\n * invoke facet/RPC-stub methods with `Reflect.apply(fn, receiver, args)`, NEVER `stub[m].apply(stub,\n * args)`. Reading `.apply` off an RPC stub's method proxy is a capnweb PIPELINED REMOTE PATH;\n * calling it passes the stub as an argument, so workerd serializes it — and a Worker-Loader facet\n * stub may never be serialized (`requireAllowsTransfer()` throws unconditionally) → `DataCloneError:\n * Durable Object Facet stubs cannot be transferred between Workers`. Do not \"simplify\" this away.\n */\nexport async function walkSteps(\n start: { value: unknown; receiver: unknown },\n steps: ItxExpression,\n): Promise<{ value: unknown; receiver: unknown }> {\n let { value, receiver } = start;\n for (const [stepIndex, step] of steps.entries()) {\n if (!pipelined(value)) value = await value;\n if (value == null)\n throw new Error(\n `hit ${String(value)} at step ${stepIndex + 1} of ${print(steps)} (${JSON.stringify(step)})`,\n );\n if (typeof step === \"string\") {\n receiver = value;\n value = stepGet(value as object, step);\n } else {\n const [method, ...args] = step;\n if (method === \"\") {\n // the ANONYMOUS call step (expression.ts): call the value itself — a live stub's root call\n value = callOn(value, receiver, args);\n receiver = undefined;\n if (!pipelined(value)) value = await value;\n continue;\n }\n const fn = stepGet(value as object, method);\n if (typeof fn !== \"function\")\n throw codedError(\n \"NOT_A_METHOD\",\n `${JSON.stringify(method)} is not a method at step ${stepIndex + 1} of ${print(steps)}`,\n );\n receiver = undefined;\n value = Reflect.apply(fn, value, args);\n if (!pipelined(value)) value = await value;\n }\n }\n return { value: pipelined(value) ? value : await value, receiver };\n}\n\n/** Apply `args` to a resolved value on its carried receiver, or a LOUD error if it is not callable\n * (never the silent arg-drop apps/os shipped). An `InvokeHandle` is NOT a JS function (a real\n * RpcTarget so dotted access pipelines — the invoke handle section), so ROOT-calling it dispatches\n * those args at its EMPTY path: `handle(events,range)` ⇒ the bare callback the handle fronts. The one\n * bridge between \"callable capability\" and \"pipelinable RpcTarget\". */\nexport async function callOn(value: unknown, receiver: unknown, args: unknown[]): Promise<unknown> {\n if (typeof value === \"function\") return Reflect.apply(value, receiver, args);\n if (value instanceof InvokeHandle) return value.applyRoot(args);\n throw codedError(\"NOT_A_METHOD\", `target is not callable but ${args.length} arg(s) were passed`);\n}\n\n// ── invoke handle ── THE DOTTED DOOR: how a surface that declares only fixed methods is\n// spoken as deep dotted access (`itx.slack.chat.postMessage({...})`), every unknown segment\n// accumulating into ONE `invoke(expression)` dispatch, `[...root, ...prefix, [method, ...args]]`.\n// Declared members always win. The pieces: the reserved names, the function-backed PATH PROXY, the\n// PROTOTYPE HOP that installs the fallback on a class, `InvokeHandle` (the genuine RpcTarget a\n// mid-chain capability is handed back as), and `walkStepsOnRpcStub`.\n//\n// WHY A PROTOTYPE HOP AND NOT A PROXY AROUND THE INSTANCE (tried FIRST and reverted): workerd RPC\n// classifies a call's RESULT for promise pipelining with native brand checks a JS Proxy can never\n// pass (`serializeJsValueWithPipeline` in worker-rpc.c++ → `NonPipelinable`; cloudflare/workerd#6873).\n// So a surface returned FROM A METHOD must hand back a REAL, unproxied instance or every pipelined\n// call on it dies with \"The RPC receiver does not implement the method ...\". A mid-chain call\n// returns its handle ACROSS an RPC boundary (`itx.facets.get('b').hello()` is two dispatches), and\n// capnweb's RpcTarget IS the native `cloudflare:workers` RpcTarget on workerd, so a real RpcTarget\n// passes on both hops. The hop squares that with dynamic dispatch by inserting one proxied link\n// BETWEEN `Class.prototype` and its parent:\n//\n// instance ──proto──▶ Class.prototype ──proto──▶ Proxy(hop) ──proto──▶ parent\n//\n// - The instance is a genuine, natively-branded RpcTarget → the pipeline classifier accepts it.\n// - Declared members resolve BEFORE the hop — built-ins win, so a dynamic capability can never\n// shadow a declared name (the deliberate trade-off).\n// - Unknown string keys reach the hop's `get` trap and become path proxies, dispatched via the\n// receiver's own `invoke`; the receiver IS the invoker, so it wires with zero glue.\n// - Instances stay clean of own properties, so Workers RPC's instance-property protection needs\n// no `getOwnPropertyDescriptor` help.\n//\n// KNOWN QUIRKS (accepted, by parity with apps/os): no `has` trap on the hop, so `\"x\" in instance`\n// reflects DECLARED members only while `instance.x` conjures a dispatcher — feature-detect with\n// access, not `in`; a typo'd built-in (`itx.strems`) is a syntactically valid dynamic dispatch that\n// fails at the capability table, not a crisp missing-method error.\n//\n// The library tier may import this module and the codec only (library.test.ts).\n\n/** The dispatch door every dotted miss collapses onto. `IterateContextRpcTarget` implements it directly (root\n * `itx`); a mid-chain `InvokeHandle` implements it relative to itself (empty root). */\ntype InvokeTarget = {\n invoke(itxExpression: ItxExpression): unknown;\n};\n\n/** Names that must NEVER become dynamic capability segments — a dispatcher answering them would turn\n * a plain property probe into a live capability call. Enforced at the prototype-chain hop and at\n * every depth of the path proxies it hands out. Two kinds, one set: */\nconst RESERVED_SEGMENT_NAMES: ReadonlySet<string> = new Set([\n // JS/RPC protocol machinery a framework or capnweb probes on any object (`then` above all: an\n // instance must never look thenable, or every `await` of it would resolve a capability).\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n \"__proto__\",\n \"apply\",\n \"bind\",\n \"call\",\n \"catch\",\n \"constructor\",\n \"dup\",\n \"finally\",\n \"hasOwnProperty\",\n \"isPrototypeOf\",\n \"map\",\n \"onRpcBroken\",\n \"propertyIsEnumerable\",\n \"prototype\",\n \"then\",\n \"toLocaleString\",\n \"toString\",\n \"valueOf\",\n // Names common protocols LOOK UP on arbitrary objects and CALL if callable: JSON.stringify\n // (toJSON) and vitest/jest equality (asymmetricMatch). The asymmetricMatch case is worse than\n // noise — vitest treats any object with a callable asymmetricMatch as an asymmetric matcher, and\n // a dispatcher returning a (truthy) Promise makes the equality SPURIOUSLY PASS. The bar for this\n // half is HIGH (these names become unreachable as dotted segments; explicit invoke still\n // reaches them): probed-and-called by ubiquitous protocols AND implausible as capability names.\n \"toJSON\",\n \"asymmetricMatch\",\n]);\n\n/** The path proxy: a function-backed Proxy (not an RpcTarget instance) — each missing property\n * extends `path`, and applying the function reduces the whole accumulated access into ONE\n * `invoke(expression)` call, `[...root, ...path.slice(0, -1), [path.at(-1), ...args]]`. */\nfunction createItxExpressionPathProxy(\n invoker: InvokeTarget,\n root: readonly string[],\n path: string[],\n): unknown {\n const valueFor = (key: string) => createItxExpressionPathProxy(invoker, root, [...path, key]);\n return new Proxy(function () {}, {\n apply(_target, _thisArg, args) {\n const method = path[path.length - 1];\n const expr: ItxExpression = [...root, ...path.slice(0, -1), [method, ...(args as unknown[])]];\n return invoker.invoke(expr);\n },\n get(target, key, receiver) {\n if (typeof key === \"symbol\") return Reflect.get(target, key, receiver);\n if (RESERVED_SEGMENT_NAMES.has(key)) return undefined;\n return valueFor(key);\n },\n getOwnPropertyDescriptor(target, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (descriptor) return descriptor;\n if (typeof key === \"symbol\" || RESERVED_SEGMENT_NAMES.has(key)) return undefined;\n // Cap'n Web's server-side path traversal probes own descriptors before reading a segment, so\n // dynamic roots must look discoverable here to reach the apply trap.\n return { configurable: true, enumerable: true, value: valueFor(key), writable: false };\n },\n has(target, key) {\n if (typeof key === \"symbol\") return key in target;\n return !RESERVED_SEGMENT_NAMES.has(key);\n },\n });\n}\n\n/** Install the hop drawn in the header on a class's PROTOTYPE CHAIN, with the scope `root` (`[\"itx\"]`\n * for the edge context, `[]` for a handle). Call ONCE per class. Constructor inheritance is\n * untouched — only `Class.prototype`'s parent link changes, and the hop forwards everything it does\n * not intercept. */\nexport function installPrototypeInvokeFallback<T extends abstract new (...args: never[]) => object>(\n cls: T,\n root: readonly string[],\n): void {\n const parentPrototype = Object.getPrototypeOf(cls.prototype) as object;\n const hop = new Proxy(Object.create(parentPrototype) as object, {\n get(hopTarget, key, receiver) {\n // Symbols and anything the parent chain already answers (dispose protocol, capnweb\n // internals, Object.prototype) pass through with the instance as receiver.\n if (typeof key === \"symbol\" || key in hopTarget) {\n return Reflect.get(hopTarget, key, receiver);\n }\n if (RESERVED_SEGMENT_NAMES.has(key)) return undefined;\n // The dynamic fallback exists for INSTANCES. A lookup whose receiver is not one — someone\n // probing `Class.prototype.foo` directly, a framework walking prototypes — must see plain\n // \"undefined\", not conjure a dispatcher over an uninitialized receiver.\n if (!(receiver instanceof (cls as unknown as abstract new (...args: never[]) => object))) {\n return undefined;\n }\n // The receiver IS the invoker (it implements invoke). Its method resolves at CALL\n // time, so a trap firing mid-construction (a property miss on `this` before field initializers\n // ran) can't bake a dispatcher over half-initialized state into the path proxy.\n return createItxExpressionPathProxy(receiver as unknown as InvokeTarget, root, [key]);\n },\n });\n Object.setPrototypeOf(cls.prototype, hop);\n}\n\n/** A branded, pipelinable handle for a MID-CHAIN capability (`facets.get(name)`, `cd(path)`,\n * `workers.get(spec)`, a lent stub) whose unknown dotted members reduce into ONE dispatch of the\n * itx-expression STEPS relative to it; the constructor's `dispatch` routes those steps into the\n * underlying object. Declared members (`invoke` / `applyRoot`) win over the fallback, so a\n * capability cannot be named either — the two reserved words this wrapper adds. */\nexport class InvokeHandle extends RpcTarget {\n readonly #dispatchItxExpressionSteps: (itxExpressionSteps: ItxExpression) => unknown;\n constructor(dispatchItxExpressionSteps: (itxExpressionSteps: ItxExpression) => unknown) {\n super();\n this.#dispatchItxExpressionSteps = dispatchItxExpressionSteps;\n }\n /** THE reduce door the prototype hop dispatches onto; the expression is RELATIVE to this handle. */\n invoke(itxExpressionSteps: ItxExpression): unknown {\n return this.#dispatchItxExpressionSteps(itxExpressionSteps);\n }\n /** Call the bare capability this handle fronts — the ANONYMOUS call step (`callOn` in the dispatch section\n * uses it when a rewritten call's target IS a handle: `handle(events, range)`). */\n applyRoot(args: unknown[]): unknown {\n return this.#dispatchItxExpressionSteps([[\"\", ...args]]);\n }\n}\ninstallPrototypeInvokeFallback(InvokeHandle, []);\n\n/** Walk itx-expression steps off a capnweb stub; the ANONYMOUS call step (`\"\"`) calls the value\n * itself (a bare function lent as a capability). NO await inside the loop: on a capnweb stub every\n * step is a PIPELINED path, so an n-step chain costs ONE round trip, flushed by the caller's single\n * await. A DIRECT call on the stub, never `.apply`: reading `.apply` off a capnweb stub's method is\n * itself a pipelined remote path (`walkSteps`'s DataCloneError learning). Exported for the library\n * tier, which may import this module only. */\nexport function walkStepsOnRpcStub(stub: unknown, steps: ItxExpression): unknown {\n let value: unknown = stub;\n for (const step of steps) {\n if (typeof step === \"string\") value = (value as Record<string, unknown>)[step];\n else {\n const [method, ...args] = step;\n value =\n method === \"\"\n ? (value as (...a: unknown[]) => unknown)(...args)\n : (value as Record<string, (...a: unknown[]) => unknown>)[method](...args);\n }\n }\n return value;\n}\n\n// ── the two BRANDS the subscription delivery loop reads: the kinds that OWN THEIR PROGRESS, so a push\n// needs no cursor on the stream side (subscription-delivery.ts). Nothing is declared on any event;\n// the brand is minted where the built-in mints the handle. ──\n\n/** `itx.facets.get(name)` / `itx.facets.get(name, { source, className })` — a facet of this context. */\nexport class FacetHandle extends InvokeHandle {}\n\n/** A HANDLE ON THE WIRE IS THE EXPRESSION THAT NAMES IT. An `InvokeHandle` a context mints (`repos.get(path)`,\n * `workspaces.get(path)`, `facets.get(name)`, `cd(path)`, `workers.get(spec)`) holds no state — it is a\n * dispatch closure over a path — yet as a Workers-RPC result it would cross a hop as a LIVE stub whose\n * session keeps the context's actor resident for as long as the holder keeps it (prd 2026-09-22: ~125\n * such sessions parked around the clock). So the context's RPC door answers with THIS instead: the\n * caller's own expression, which from the caller's root denotes the same handle; the caller mints its\n * own handle over it (`materializeItxHandleReference`), and every later verb is one whole call the\n * context resolves from scratch. Nothing outlives a call. A lent client stub (`RpcStubHandle`) is the\n * one handle that IS live and crosses as itself. */\nexport const ITX_HANDLE_REFERENCE_KEY = \"$itxHandleExpression\";\nexport type ItxHandleReference = { [ITX_HANDLE_REFERENCE_KEY]: ItxExpression };\n\nexport const isItxHandleReference = (value: unknown): value is ItxHandleReference =>\n Boolean(value) &&\n typeof value === \"object\" &&\n Array.isArray((value as Record<string, unknown>)[ITX_HANDLE_REFERENCE_KEY]);\n\n/** What a context's RPC door hands back for `expression`'s result: a reference when the result is a\n * path-shaped handle (an `InvokeHandle` that is not a lent stub) or a reference from a hop below —\n * re-rooted, since `expression` is how THIS caller reached it — else nothing (the result crosses as it\n * is). Runtime args that fold into a terminal NAME fold here exactly as the resolver folds them, so the\n * reference is the call the resolver ran; args left over apply to the value and never name a handle. */\nexport function itxHandleReferenceOf(\n result: unknown,\n expression: ItxExpression,\n args: unknown[] = [],\n): ItxHandleReference | undefined {\n const last = expression.at(-1);\n const folded =\n args.length > 0 && typeof last === \"string\" && expression.length > 1\n ? [...expression.slice(0, -1), [last, ...args] as ItxExpressionStep]\n : args.length > 0\n ? undefined\n : expression;\n if (!folded) return undefined;\n const isPathShapedHandle = result instanceof InvokeHandle && !(result instanceof RpcStubHandle);\n if (!isPathShapedHandle && !isItxHandleReference(result)) return undefined;\n return { [ITX_HANDLE_REFERENCE_KEY]: folded };\n}\n\n/** The holder's side: a reference becomes a handle of the HOLDER's own whose every dotted call is one\n * whole expression through `invoke` — the reference's expression plus the steps. Anything else passes\n * through untouched. The proxy hands relative steps; a caller's own `.invoke(\"itx.whoami()\")` is a\n * whole call, spelled from the root. */\nexport function materializeItxHandleReference(\n result: unknown,\n invoke: (expression: ItxExpression) => unknown,\n): unknown {\n if (!isItxHandleReference(result)) return result;\n const expression = result[ITX_HANDLE_REFERENCE_KEY];\n return new InvokeHandle((steps) =>\n invoke(\n typeof steps === \"string\" || steps[0] === \"itx\"\n ? normalizedItxExpression(steps as ItxExpressionInput)\n : [...expression, ...steps],\n ),\n );\n}\n/** `itx.rpcStubs.get(key)` — a live stub lent to the registry. */\nexport class RpcStubHandle extends InvokeHandle {}\n"],"mappings":";;;;;;;;AAeA,MAAM,kCAAkC;;AAsBxC,MAAa,yBAAyB,SACpC,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK;AAElC,MAAM,QAAQ;AACd,MAAM,WAAW,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAUlE,MAAM,sBAAsB,EAAE,KAAK,KAAK;;AAExC,MAAa,2BAA2B;;;;;AAMxC,MAAM,oBAAoB,OAAO,GAAG;AACpC,MAAM,qBAAqB,UACzB,MA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AAO,SAAS,YAAY,WAAW,SAAS,IAC/D,CAAC,GAAG,WAAW,MAAM,GAAG,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAsB,IACjE,KAAK,SAAS,IACZ,KAAA,IACA;CACR,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,IAAI,EADuB,kBAAkB,gBAAgB,EAAE,kBAAkB,mBACtD,CAAC,qBAAqB,MAAM,GAAG,OAAO,KAAA;CACjE,OAAO,GAAG,2BAA2B,OAAO;AAC9C;;;;;AAMA,SAAgB,8BACd,QACA,QACS;CACT,IAAI,CAAC,qBAAqB,MAAM,GAAG,OAAO;CAC1C,MAAM,aAAa,OAAO;CAC1B,OAAO,IAAI,cAAc,UACvB,OACE,OAAO,UAAU,YAAY,MAAM,OAAO,QACtC,wBAAwB,KAA2B,IACnD,CAAC,GAAG,YAAY,GAAG,KAAK,CAC9B,CACF;AACF;;AAEA,IAAa,gBAAb,cAAmC,aAAa,CAAC"}
|
package/dist/next/lib.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"lib.mjs","names":[],"sources":["../../src/next/lib.ts"],"sourcesContent":["// lib.ts — the pure helpers every layer shares; four concepts, one platform-neutral file (it rides\n// the SDK bundle and the node unit lane, so no cloudflare:workers here):\n// errors — `codedError` / `errorCode` / `reportIssue`: THE machine-readable error channel\n// patch — `diff` / `applyPatch` / `jsonEqual`: the live-state delta (an RFC 6902 subset)\n// timeout — `withTimeout`: a promise raced against a deadline (code TIMEOUT)\n// origin — `isSameOriginBrowserRequest`: may a request spend the cookies it carries\n\n// ── errors ── THE machine-readable error channel, after cloudflare-os\n// (workshop-shared/src/api.ts: plain Error + a `code` own-property via Object.assign, read with\n// `\"code\" in error`). Why this shape and no other: capnweb coerces custom error NAMES to a\n// builtin whitelist and drops subclass identity, but preserves ALL own enumerable properties\n// across the wire (verified at runtime against @iterate-com/capnweb 0.10.0) — and with\n// enhanced_error_serialization (our compat date) own props survive native Workers-RPC hops too.\n// So: never classify by `name`, `instanceof`, or message regex across a hop; check the code.\n// Human messages stay verbatim and greppable — the code rides beside them, never instead.\n// workerd's own stamped flags (`.retryable`, `.overloaded`, `.durableObjectReset`) ride the same\n// own-property channel; honor them rather than inventing a retry taxonomy.\n\n/** The stable machine-readable codes — SCREAMING_SNAKE, defined once, both ends import this. */\ntype ErrorCode =\n | \"SCHEDULE_LIMIT\" // bounded pending/failed scheduled batches per context\n | \"INVALID_INPUT\"\n | \"IDENTITY_CONFLICT\" // verified login cannot replace another linked identity\n | \"GRANT_NOT_FOUND\" // a caller may revoke only a grant in their own inventory\n | \"NO_ITX_EXPRESSION_MATCH\" // no rewrite rule matches the call (default-deny)\n | \"IDEMPOTENCY_CONFLICT\"\n | \"OFFSET_CONFLICT\" // an input's expected `offset` is not the offset it would land at\n | \"EVENT_TOO_LARGE\" // one event's serialized body is over the append ceiling (stream.ts EVENT_BODY_MAX_CHARS)\n | \"REDUCE_CHECKPOINT_TOO_LARGE\" // a reduce's state would not fit one storage cell (stream/processor.ts)\n | \"EVENT_UNREADABLE\" // a stored row's body is not JSON — `data.offset` names it (stream.ts read)\n | \"STREAM_PAUSED\"\n | \"INVALID_CONTEXT\" // a context name / project id the codec refuses (iterate-context.ts `DurableObjectNameCodec`) — coded, so it survives the hop\n | \"EXPRESSION_TOO_LONG\" // a STRING itx expression over ITX_EXPRESSION_STRING_MAX_CHARS — pass the parsed form\n | \"FACET_SOURCE_TOO_LARGE\" // a facet's literal source over FACET_SOURCE_MAX_CHARS (worker-loader.ts) — refused at the door\n | \"INVALID_CREDENTIALS\" // authenticate(): the admin secret did not match, or the credentials named no known kind\n | \"UNAUTHENTICATED\" // authenticate({ type: \"from-server-cookie\" }): no session cookie on the request, or a cross-origin browser's request\n | \"FORBIDDEN\" // projects.get(project): outside the session's reach (a grant narrowed to other projects, or the user is no member of its org); create on a narrowed grant; grants/consent on a session that carries none; organizations.get outside the session's memberships; `cd` in the global namespace (a global context is reached by identity, never by path)\n | \"PROJECT_NAME_TAKEN\" // projects.create({ project }): a project of that slug exists in another org\n | \"RPC_STUB_OFFLINE\" // the rpc stub a row names is neither borrowed nor pager-backed right now — or its lend ended mid-call (recalled, returned, broken; the relay re-codes)\n | \"NOT_A_METHOD\" // the dotted path's terminal segment is not callable on the target\n | \"NO_FACET\" // no facet of that name has been loaded into this context\n | \"FACET_NO_UPGRADE\" // a WebSocket upgrade aimed at a facet: a facet answers RPC and plain HTTP, never a socket — sockets terminate at the edge (apps/os-next context/facet-host.ts)\n | \"WAIT_TIMEOUT\" // waitForEvent expired with no matching event committed\n | \"TIMEOUT\"; // lib.ts withTimeout: the call did not answer within its deadline\n// (There is no separate boundary-validation library: the append door's own runtime guards\n// throw plain Errors; a client is JUST capnweb, so malformed args surface as ordinary errors.)\n\n/** A plain Error carrying `code` (+ optional `data`) as own enumerable properties. */\nexport function codedError(code: ErrorCode, message: string, data?: unknown): Error {\n return Object.assign(new Error(message), data === undefined ? { code } : { code, data });\n}\n\n/** The code of an error that crossed any number of hops — undefined for uncoded errors. */\nexport function errorCode(error: unknown): ErrorCode | undefined {\n return typeof error === \"object\" && error && \"code\" in error\n ? ((error as { code: unknown }).code as ErrorCode)\n : undefined;\n}\n\n// reportIssue — the ONE exit for unexpected failures (cloudflare-os error-reporting.ts, minus\n// its private Reporter Worker): one bounded console.error line; query event=\"issue\" in Workers\n// Logs. The Reporter seam stayed out on purpose — when one exists, check an optional env\n// binding HERE and waitUntil the dispatch; capture sites never change. Deliberately NO\n// cloudflare:workers import: this file rides the platform-neutral SDK bundle. Reporting must\n// never disturb the caller — armored end to end; worst case it prints nothing.\n\n// Bounds verbatim from cloudflare-os: hostile strings get clipped, never explode a log line.\nconst MAX = { message: 1024, stack: 16_384, string: 256, attributeKeys: 32 } as const;\ntype Scalar = string | number | boolean | null; // attribute values stay queryable scalars\n\n/** Print ONE bounded console.error line for an unexpected failure; never throws. */\nexport function reportIssue(\n failureSite: string,\n caught: unknown,\n attributes?: Record<string, Scalar | undefined>,\n): void {\n try {\n const bounded: Record<string, Scalar> = {};\n for (const [key, value] of Object.entries(attributes || {}).slice(0, MAX.attributeKeys)) {\n if (value === undefined) continue;\n bounded[key.slice(0, MAX.string)] =\n typeof value === \"string\" ? value.slice(0, MAX.string) : value;\n }\n const code = errorCode(caught);\n // The thrown value, bounded — name/message/stack read off an Error; an arbitrary object is\n // never walked.\n const error =\n caught instanceof Error\n ? {\n type: (caught.name || \"Error\").slice(0, MAX.string),\n message: caught.message.slice(0, MAX.message),\n ...(caught.stack && { stack: caught.stack.slice(0, MAX.stack) }),\n }\n : typeof caught === \"object\" && caught\n ? { type: \"ObjectThrown\" }\n : { type: `${typeof caught}Thrown`, message: String(caught).slice(0, MAX.message) };\n console.error({\n ...bounded, // fixed keys spread last so an attribute can never shadow them\n event: \"issue\",\n failureSite: failureSite.slice(0, MAX.string),\n code,\n error,\n });\n } catch {\n // Reporting must never disturb the caller — swallow and move on.\n }\n}\n\n// ── patch ── the LiveView-style delta that rides every live-state change event. `diff` runs at\n// the PRODUCER (the processor's reduce, the mini-app helper's set) where old and new value are\n// both in hand; the stream forwards the ops verbatim; only CLIENTS apply them. The format is an\n// RFC 6902 subset (add / replace / remove, JSON-Pointer paths) so any off-the-shelf json-patch\n// library applies our patch payloads — we invent no wire format, we just never emit the exotic ops.\n\nexport type PatchOp =\n | { op: \"add\"; path: string; value: unknown }\n | { op: \"replace\"; path: string; value: unknown }\n | { op: \"remove\"; path: string };\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && !!v && !Array.isArray(v);\n\nconst escape = (seg: string | number): string =>\n String(seg).replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n\n/** Structural deep-equal over plain JSON values — order-insensitive, unbudgeted (JSON is acyclic).\n * THE one deep-equal: the live-state diff's \"don't emit\" test AND the idempotency-body compare\n * (re-exported through stream/processor.ts). The `Object.hasOwn(b, k)` guard is load-bearing — without\n * it, two objects with the same key COUNT but different key SETS compare equal. */\nexport function jsonEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => jsonEqual(v, b[i]));\n if (isRecord(a) && isRecord(b)) {\n const ka = Object.keys(a);\n return (\n ka.length === Object.keys(b).length &&\n ka.every((k) => Object.hasOwn(b, k) && jsonEqual(a[k], b[k]))\n );\n }\n return false;\n}\n\n/** Structural diff `a → b`, or undefined when deep-equal (the producer's \"don't emit\" signal).\n * Objects recurse per key; arrays get the chat-log fast paths (pure append → `add …/-` ops,\n * pure tail-truncate → `remove` ops) and are replaced wholesale on any middle divergence —\n * the LiveView trade: optimize the growing log, full-render the rewrite.\n * Both sides are JSON-normalized first — the wire is JSON, so the diff must see exactly what\n * the wire will carry: undefined-valued keys vanish, Dates become their ISO strings, array\n * holes become null. Diffing what you didn't normalize is how a Date change goes silent. */\nexport function diff(a: unknown, b: unknown): PatchOp[] | undefined {\n // stringify can itself return undefined (a bare function, toJSON() → undefined) — parse\n // would then throw SyntaxError('\"undefined\" is not valid JSON'); treat those as absent.\n const json = (v: unknown) => {\n const s = JSON.stringify(v);\n return s ? (JSON.parse(s) as unknown) : undefined;\n };\n return walk(json(a), json(b), \"\");\n}\n\nfunction walk(a: unknown, b: unknown, path: string): PatchOp[] | undefined {\n if (jsonEqual(a, b)) return undefined;\n if (Array.isArray(a) && Array.isArray(b)) {\n const shared = Math.min(a.length, b.length);\n let p = 0;\n while (p < shared && jsonEqual(a[p], b[p])) p++;\n if (p === a.length) return b.slice(p).map((value) => ({ op: \"add\", path: `${path}/-`, value }));\n if (p === b.length)\n return a\n .slice(p)\n .map((_, i) => ({ op: \"remove\", path: `${path}/${a.length - 1 - i}` }) as const);\n return [{ op: \"replace\", path, value: b }];\n }\n if (isRecord(a) && isRecord(b)) {\n const ops: PatchOp[] = [];\n for (const k of Object.keys(a))\n if (!Object.hasOwn(b, k)) ops.push({ op: \"remove\", path: `${path}/${escape(k)}` });\n for (const k of Object.keys(b)) {\n if (!Object.hasOwn(a, k)) ops.push({ op: \"add\", path: `${path}/${escape(k)}`, value: b[k] });\n else ops.push(...(walk(a[k], b[k], `${path}/${escape(k)}`) ?? []));\n }\n return ops.length ? ops : undefined;\n }\n return [{ op: \"replace\", path, value: b }];\n}\n\n/** Apply a patch non-mutatingly (clone-then-mutate). The client half of `diff` — exported\n * through the SDK so subscribers need no third-party json-patch dependency. */\nexport function applyPatch<T>(doc: T, ops: PatchOp[]): T {\n let root: unknown = structuredClone(doc);\n for (const op of ops) {\n if (op.path === \"\") {\n if (op.op === \"remove\") throw new Error(\"applyPatch: cannot remove the document root\");\n root = op.value;\n continue;\n }\n const segs = op.path\n .slice(1)\n .split(\"/\")\n .map((s) => s.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n // Patches arrive over the wire. \"__proto__\" is refused outright (assigning it invokes the\n // prototype setter, not a property write); other prototype members (\"constructor\", …) are\n // ordinary keys — traversal below is own-property-only, so the chain is never walked.\n for (const s of segs)\n if (s === \"__proto__\") throw new Error(`applyPatch: refusing __proto__ in path ${op.path}`);\n const last = segs.pop()!;\n let parent: unknown = root;\n for (const s of segs) {\n parent = Array.isArray(parent)\n ? parent[Number(s)]\n : isRecord(parent) && Object.hasOwn(parent, s)\n ? parent[s]\n : undefined;\n if (parent === undefined) throw new Error(`applyPatch: missing path ${op.path}`);\n }\n if (Array.isArray(parent)) {\n if (op.op === \"add\") {\n if (last === \"-\") parent.push(op.value);\n else parent.splice(Number(last), 0, op.value);\n } else if (op.op === \"replace\") parent[Number(last)] = op.value;\n else parent.splice(Number(last), 1);\n } else if (isRecord(parent)) {\n if (op.op === \"remove\") delete parent[last];\n else parent[last] = op.value;\n } else throw new Error(`applyPatch: path ${op.path} traverses a non-container`);\n }\n return root as T;\n}\n\n// ── timeout ── race a promise against a deadline. The timer is CLEARED on every exit: a leaked\n// timer per call would pin a Durable Object awake. A loss rejects with code TIMEOUT so a caller can\n// tell \"took too long\" from the call's own failure (the DO's facet watchdog aborts the facet on it).\n//\n// `what` may be a THUNK: a label whose construction is expensive (the facet watchdog prints the whole\n// pushed batch) is built ONLY when the deadline is actually lost, off the per-call hot path.\n\nexport async function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n what: string | (() => string),\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n codedError(\n \"TIMEOUT\",\n `${typeof what === \"function\" ? what() : what}: no answer in ${ms / 1000}s`,\n ),\n ),\n ms,\n );\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n// ── origin ── the one check that makes an ambient cookie safe to honour (session.ts\n// `from-server-cookie`, the issuer's form posts in os-next issuer-pages.ts).\n\n/** Whether `request` may spend the cookies it carries: its `Origin` header is this origin, or absent\n * (a non-browser client — curl, a script). A browser stamps the page's origin on every WebSocket\n * handshake, every cross-site fetch and every form POST, so a foreign origin means a foreign site\n * drove the request with the visitor's cookie riding along. A malformed `Origin` (the literal\n * `null` of a sandboxed document included) is foreign. */\nexport function isSameOriginBrowserRequest(request: Pick<Request, \"url\" | \"headers\">): boolean {\n const origin = request.headers.get(\"origin\");\n // oxlint-disable-next-line iterate/simple-truthiness-check -- security: only a truly absent Origin (non-browser client) is trusted; an empty \"\" Origin header must stay foreign, which a truthiness check would wrongly accept\n if (origin === null) return true;\n try {\n return new URL(origin).origin === new URL(request.url).origin;\n } catch {\n return false;\n }\n}\n\n/** `next` as a path on `origin`, else \"/\" — a redirect never leaves the host: `//evil.example`,\n * `/\\evil.example` and an absolute URL all resolve to a foreign origin and fall back to \"/\". The\n * issuer's login redirect uses it too (os-next issuer-pages.ts). */\nexport function sameOriginPath(next: string, origin: string): string {\n try {\n const url = new URL(next, origin);\n return url.origin === origin ? url.pathname + url.search : \"/\";\n } catch {\n return \"/\";\n }\n}\n\n/** Only plain HTTP loopback origins use development login and client registration. */\nexport function isLocalOrigin(origin: string) {\n const url = new URL(origin);\n return (\n url.protocol === \"http:\" &&\n (url.hostname === \"localhost\" ||\n url.hostname.endsWith(\".localhost\") ||\n url.hostname === \"127.0.0.1\")\n );\n}\n\n/** Resolve a `cd` target against a context's own path — the one resolver every `cd` (the edge\n * method, the built-in root, the library's relative handles) shares. Absolute (\"/agents/x\") stands alone; relative\n * (\"agents/x\", \"../inbox\", \".\") joins onto `base`. `.` and `..` resolve; the root cannot be\n * escaped (\"/..\" is \"/\"). The result is canonical: leading slash, no trailing slash but for \"/\". */\nexport function resolveContextPath(basePath: string, contextPath: string): string {\n const segments: string[] = [];\n for (const seg of `${contextPath.startsWith(\"/\") ? \"\" : basePath}/${contextPath}`.split(\"/\")) {\n if (seg === \"\" || seg === \".\") continue;\n if (seg === \"..\") segments.pop();\n else segments.push(seg);\n }\n return `/${segments.join(\"/\")}`;\n}\n"],"mappings":";;AAgDA,SAAgB,WAAW,MAAiB,SAAiB,MAAuB;CAClF,OAAO,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,SAAS,KAAA,IAAY,EAAE,KAAK,IAAI;EAAE;EAAM;CAAK,CAAC;AACzF;;AAGA,SAAgB,UAAU,OAAuC;CAC/D,OAAO,OAAO,UAAU,YAAY,SAAS,UAAU,QACjD,MAA4B,OAC9B,KAAA;AACN;AAUA,MAAM,MAAM;CAAE,SAAS;CAAM,OAAO;CAAQ,QAAQ;CAAK,eAAe;AAAG;;AAI3E,SAAgB,YACd,aACA,QACA,YACM;CACN,IAAI;EACF,MAAM,UAAkC,CAAC;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,IAAI,aAAa,GAAG;GACvF,IAAI,UAAU,KAAA,GAAW;GACzB,QAAQ,IAAI,MAAM,GAAG,IAAI,MAAM,KAC7B,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG,IAAI,MAAM,IAAI;EAC7D;EACA,MAAM,OAAO,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AI,QAAQ,MAAM,QAAQ,KAAK;EAC/B,IAAI,QAAQ,MAAM,SAAS,IAAI;OAC1B,SAAS,KAAK,GAAG;CACxB;CACA,OAAO,IAAI,SAAS,KAAK,GAAG;AAC9B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-scopes.mjs","names":[],"sources":["../../src/next/oauth-scopes.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/** The platform's OAuth scopes — what an app may ask for and what a consent grants:\n * - `iterate` — reach the projects the person grants (every app; implied, always granted)\n * - `account` — manage the person's sessions and personal access tokens\n * - `organizations:write` — the person's organizations: list every one they belong to, create new ones\n * Consent is task-based (the shape Cloudflare's own OAuth consent took in August 2026: a client\n * requests a set, the person may deselect the optional ones, the token carries what was granted):\n * `iterate` is required, every other requested scope is optional on the consent page, and an app\n * reads the granted set from `session.info().scopes` rather than assuming its request. */\nexport const OAuthScope = z.enum([\"iterate\", \"account\", \"organizations:write\"]);\nexport type OAuthScope = z.infer<typeof OAuthScope>;\n\nexport const OAuthScopes = z\n .array(OAuthScope)\n .transform((scopes) => [...new Set([\"iterate\", ...scopes])]);\n\n/** A requested scope as the consent page shows it: its name, what it means to the person, and\n * whether they may untick it (`iterate` never). */\nexport interface ConsentScope {\n name: OAuthScope;\n title: string;\n note: string;\n required: boolean;\n}\n\n/** What each scope means to the person — the consent page's copy, sent with `consent.describe` so\n * the page renders what it is given: a scope added to `OAuthScope` is described here or it does\n * not compile. */\nexport const OAuthScopeDescriptions: Record<OAuthScope, Omit<ConsentScope, \"name\">> = {\n iterate: {\n title: \"Read and make changes in the projects you grant it\",\n note: \"Required — what the app is for.\",\n required: true,\n },\n account: {\n title: \"See and end your sessions, and mint personal access tokens\",\n note: \"Optional.\",\n required: false,\n },\n \"organizations:write\": {\n title: \"See all your organizations and create new ones\",\n note: \"Optional.\",\n required: false,\n },\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAa,aAAa,EAAE,KAAK;CAAC;CAAW;CAAW;AAAqB,CAAC;AAG9E,MAAa,cAAc,EACxB,MAAM,UAAU,CAAC,CACjB,WAAW,WAAW,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC;;;;AAc7D,MAAa,yBAAyE;CACpF,SAAS;EACP,OAAO;EACP,MAAM;EACN,UAAU;CACZ;CACA,SAAS;EACP,OAAO;EACP,MAAM;EACN,UAAU;CACZ;CACA,uBAAuB;EACrB,OAAO;EACP,MAAM;EACN,UAAU;CACZ;AACF"}
|
package/dist/next/oauth.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.mjs","names":[],"sources":["../../src/next/client/oauth.ts"],"sourcesContent":["import * as oauth from \"oauth4webapi\";\nimport { OAuthScopes } from \"../oauth-scopes.ts\";\n\n/** The same code/PKCE parameters for browser login and a console-minted token. */\nexport async function authorizationCodeRequest(input: {\n issuer: string;\n clientId: string;\n redirectUri: string;\n resources: string[];\n scopes?: string[];\n}) {\n const verifier = oauth.generateRandomCodeVerifier();\n const challenge = await oauth.calculatePKCECodeChallenge(verifier);\n const state = oauth.generateRandomState();\n const url = new URL(\"/oauth2/auth\", input.issuer);\n url.search = new URLSearchParams({\n response_type: \"code\",\n client_id: input.clientId,\n redirect_uri: input.redirectUri,\n scope: OAuthScopes.parse(input.scopes || []).join(\" \"),\n state,\n code_challenge: challenge,\n code_challenge_method: \"S256\",\n }).toString();\n for (const resource of input.resources) url.searchParams.append(\"resource\", resource);\n return { url, state, verifier };\n}\n"],"mappings":";;;;AAIA,eAAsB,yBAAyB,OAM5C;CACD,MAAM,WAAW,MAAM,2BAA2B;CAClD,MAAM,YAAY,MAAM,MAAM,2BAA2B,QAAQ;CACjE,MAAM,QAAQ,MAAM,oBAAoB;CACxC,MAAM,MAAM,IAAI,IAAI,gBAAgB,MAAM,MAAM;CAChD,IAAI,SAAS,IAAI,gBAAgB;EAC/B,eAAe;EACf,WAAW,MAAM;EACjB,cAAc,MAAM;EACpB,OAAO,YAAY,MAAM,MAAM,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;EACrD;EACA,gBAAgB;EAChB,uBAAuB;CACzB,CAAC,CAAC,CAAC,SAAS;CACZ,KAAK,MAAM,YAAY,MAAM,WAAW,IAAI,aAAa,OAAO,YAAY,QAAQ;CACpF,OAAO;EAAE;EAAK;EAAO;CAAS;AAChC"}
|
package/dist/next/principal.d.ts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
/** Who is acting: a stable actor id (the control plane's user id) and, when known, an email. */
|
|
2
|
-
export type Principal = {
|
|
3
|
-
actor: string;
|
|
4
|
-
email?: string;
|
|
5
|
-
};
|
|
6
|
-
/** WHO is making a call: the acting principal (null = anonymous). The one thing carried through every
|
|
7
|
-
* dispatch and every sibling hop (`invoke(call, args, caller)`). Set ONLY by trusted code — the edge
|
|
8
|
-
* after admission, the kernel — never by a client: the DO's `invoke` is a Workers-RPC verb, never
|
|
9
|
-
* capnweb-exposed, so a client cannot supply its own `Caller`. Authority is inferred FROM the
|
|
10
|
-
* principal (no separate scopes/trust field). Global contexts remain non-navigable through
|
|
11
|
-
* `cd`, including calls without a principal. */
|
|
12
|
-
export type Caller = {
|
|
13
|
-
principal: Principal | null;
|
|
14
|
-
/** THE CONNECTION the principal acts through: the OAuth grant's id — one per connected
|
|
15
|
-
* client (a Claude Code install, a dash sign-in, a personal token), the same across every call it
|
|
16
|
-
* makes. Absent for the admin secret and the kernel. */
|
|
17
|
-
grant?: string;
|
|
18
|
-
/** The context the call ORIGINATED at — stamped by the first `cd` hop and forwarded by every later
|
|
19
|
-
* one, so a relative path resolved after a hop (`repos.get('./x')` answered at the root) still
|
|
20
|
-
* means the caller's `./x`. Absent until a hop. Its presence also means the complete input
|
|
21
|
-
* expression was already admitted: a receiving resolver must not recheck owner-written
|
|
22
|
-
* rewrites as loaded code's input. Fresh env.ITX calls never inherit this stamp. */
|
|
23
|
-
path?: string;
|
|
24
|
-
/** Set when the caller is LOADED CODE — a worker, a facet, a script — holding a context through
|
|
25
|
-
* `env.ITX`. Under it the resolver refuses the fixed point (`itx.builtins…`) and any `cd` above
|
|
26
|
-
* the caller's own context on the INPUT expression; rewrites the owner wrote are never subject. */
|
|
27
|
-
app?: true;
|
|
28
|
-
/** THE PLATFORM ORIGIN the caller reached the platform on (os-next platform-origin.ts) — what a
|
|
29
|
-
* public URL is composed from (`itx.url`, a signed file URL). Absent for a caller with none (a
|
|
30
|
-
* loaded worker's `env.ITX`, the kernel); the context then uses the last one it was reached on. */
|
|
31
|
-
platformOrigin?: string | null;
|
|
32
|
-
};
|
|
33
|
-
/** The header the edge sets on a Request it forwards on a principal's behalf — the ingress after
|
|
34
|
-
* the cookie check, a session's terminal `fetch` — and strips from every inbound Request. */
|
|
35
|
-
export declare const ITX_PRINCIPAL_HEADER = "x-itx-principal";
|
|
36
|
-
/** The grant's header beside it (the caller's `grant`), set and stripped exactly where the
|
|
37
|
-
* principal's is. */
|
|
38
|
-
export declare const ITX_GRANT_HEADER = "x-itx-grant";
|
|
39
|
-
/** The header a loaded worker's `env.ITX.fetch` sets on the Request it forwards, so the context's
|
|
40
|
-
* fetch runs the call as app code; stripped from every Request that arrives from outside. */
|
|
41
|
-
export declare const ITX_APP_HEADER = "x-itx-app";
|
|
42
|
-
/** Originating context of a native fetch forwarded by a trusted context. */
|
|
43
|
-
export declare const ITX_CALLER_PATH_HEADER = "x-itx-caller-path";
|
|
44
|
-
/** The event as the log stores it: `source.principal` and `source.grant` are the platform's — set
|
|
45
|
-
* from the admitted caller, client-supplied ones dropped (an anonymous session's event carries
|
|
46
|
-
* neither, the kernel's none). */
|
|
47
|
-
export declare function stampCaller<E extends {
|
|
48
|
-
source?: Record<string, unknown>;
|
|
49
|
-
}>(event: E, caller: Caller): E;
|
|
50
|
-
/** Sign JSON claims: the bounded Google login flow's cookie (identity.ts). */
|
|
51
|
-
export declare function signClaims(claims: unknown, secret: string): Promise<string>;
|
|
52
|
-
/** The claims of a token that is well-formed and signed with `secret` — else null (no reason: a
|
|
53
|
-
* caller answers every bad token the same way). A blank secret verifies nothing. The caller checks
|
|
54
|
-
* the claims' SHAPE and expiry. */
|
|
55
|
-
export declare function verifyClaims(token: string, secret: string): Promise<unknown>;
|
|
56
|
-
/** The principal the admin secret grants — `{ actor: "admin" }`, every project — when `candidate`
|
|
57
|
-
* IS `secret` (`APP_CONFIG_ADMIN_API_SECRET`: at `authenticate({ type: "admin-secret" })`, as a
|
|
58
|
-
* lane's bearer and on `/mcp`), else null. Both are SHA-256 hashed and the digests compared in
|
|
59
|
-
* constant time. A blank secret matches nothing. */
|
|
60
|
-
export declare function verifyAdminSecret(candidate: string, secret: string): Promise<{
|
|
61
|
-
actor: "admin";
|
|
62
|
-
} | null>;
|
|
63
|
-
/** The value of the cookie `name` in a `Cookie` header, or null. */
|
|
64
|
-
export declare function cookieValueOf(cookieHeader: string | null, name: string): string | null;
|
package/dist/next/principal.mjs
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
//#region src/next/principal.ts
|
|
2
|
-
/** The header the edge sets on a Request it forwards on a principal's behalf — the ingress after
|
|
3
|
-
* the cookie check, a session's terminal `fetch` — and strips from every inbound Request. */
|
|
4
|
-
const ITX_PRINCIPAL_HEADER = "x-itx-principal";
|
|
5
|
-
/** The grant's header beside it (the caller's `grant`), set and stripped exactly where the
|
|
6
|
-
* principal's is. */
|
|
7
|
-
const ITX_GRANT_HEADER = "x-itx-grant";
|
|
8
|
-
/** The header a loaded worker's `env.ITX.fetch` sets on the Request it forwards, so the context's
|
|
9
|
-
* fetch runs the call as app code; stripped from every Request that arrives from outside. */
|
|
10
|
-
const ITX_APP_HEADER = "x-itx-app";
|
|
11
|
-
/** Originating context of a native fetch forwarded by a trusted context. */
|
|
12
|
-
const ITX_CALLER_PATH_HEADER = "x-itx-caller-path";
|
|
13
|
-
/** The event as the log stores it: `source.principal` and `source.grant` are the platform's — set
|
|
14
|
-
* from the admitted caller, client-supplied ones dropped (an anonymous session's event carries
|
|
15
|
-
* neither, the kernel's none). */
|
|
16
|
-
function stampCaller(event, caller) {
|
|
17
|
-
const { principal: _clientPrincipal, grant: _clientGrant, ...source } = event.source || {};
|
|
18
|
-
if (caller.principal) {
|
|
19
|
-
const stamped = {
|
|
20
|
-
...source,
|
|
21
|
-
principal: caller.principal
|
|
22
|
-
};
|
|
23
|
-
if (caller.grant) stamped.grant = caller.grant;
|
|
24
|
-
return {
|
|
25
|
-
...event,
|
|
26
|
-
source: stamped
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
return Object.keys(source).length > 0 ? {
|
|
30
|
-
...event,
|
|
31
|
-
source
|
|
32
|
-
} : (({ source: _dropped, ...rest }) => rest)(event);
|
|
33
|
-
}
|
|
34
|
-
const encoder = new TextEncoder();
|
|
35
|
-
const decoder = new TextDecoder();
|
|
36
|
-
const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
37
|
-
const bytesFromBase64url = (text) => Uint8Array.from(atob(text.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(text.length / 4) * 4, "=")), (c) => c.charCodeAt(0));
|
|
38
|
-
async function hmacKey(secret, usage) {
|
|
39
|
-
return crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
40
|
-
name: "HMAC",
|
|
41
|
-
hash: "SHA-256"
|
|
42
|
-
}, false, [usage]);
|
|
43
|
-
}
|
|
44
|
-
/** Sign JSON claims: the bounded Google login flow's cookie (identity.ts). */
|
|
45
|
-
async function signClaims(claims, secret) {
|
|
46
|
-
const payload = base64url(encoder.encode(JSON.stringify(claims)));
|
|
47
|
-
const signature = await crypto.subtle.sign("HMAC", await hmacKey(secret, "sign"), encoder.encode(payload));
|
|
48
|
-
return `${payload}.${base64url(new Uint8Array(signature))}`;
|
|
49
|
-
}
|
|
50
|
-
/** The claims of a token that is well-formed and signed with `secret` — else null (no reason: a
|
|
51
|
-
* caller answers every bad token the same way). A blank secret verifies nothing. The caller checks
|
|
52
|
-
* the claims' SHAPE and expiry. */
|
|
53
|
-
async function verifyClaims(token, secret) {
|
|
54
|
-
if (!secret) return null;
|
|
55
|
-
const dot = token.indexOf(".");
|
|
56
|
-
if (dot <= 0) return null;
|
|
57
|
-
const payload = token.slice(0, dot);
|
|
58
|
-
let signature;
|
|
59
|
-
let claims;
|
|
60
|
-
try {
|
|
61
|
-
signature = bytesFromBase64url(token.slice(dot + 1));
|
|
62
|
-
claims = JSON.parse(decoder.decode(bytesFromBase64url(payload)));
|
|
63
|
-
} catch {
|
|
64
|
-
return null;
|
|
65
|
-
}
|
|
66
|
-
return await crypto.subtle.verify("HMAC", await hmacKey(secret, "verify"), signature, encoder.encode(payload)) ? claims : null;
|
|
67
|
-
}
|
|
68
|
-
const sha256 = async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text)));
|
|
69
|
-
/** Whether two digests are the same bytes — every byte compared, no early exit, so neither a
|
|
70
|
-
* matching prefix nor its length leaks by timing. */
|
|
71
|
-
const digestsEqual = (a, b) => {
|
|
72
|
-
if (a.length !== b.length) return false;
|
|
73
|
-
let difference = 0;
|
|
74
|
-
for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i];
|
|
75
|
-
return difference === 0;
|
|
76
|
-
};
|
|
77
|
-
/** The principal the admin secret grants — `{ actor: "admin" }`, every project — when `candidate`
|
|
78
|
-
* IS `secret` (`APP_CONFIG_ADMIN_API_SECRET`: at `authenticate({ type: "admin-secret" })`, as a
|
|
79
|
-
* lane's bearer and on `/mcp`), else null. Both are SHA-256 hashed and the digests compared in
|
|
80
|
-
* constant time. A blank secret matches nothing. */
|
|
81
|
-
async function verifyAdminSecret(candidate, secret) {
|
|
82
|
-
if (!secret) return null;
|
|
83
|
-
const [candidateDigest, secretDigest] = await Promise.all([sha256(candidate), sha256(secret)]);
|
|
84
|
-
return digestsEqual(candidateDigest, secretDigest) ? { actor: "admin" } : null;
|
|
85
|
-
}
|
|
86
|
-
/** The value of the cookie `name` in a `Cookie` header, or null. */
|
|
87
|
-
function cookieValueOf(cookieHeader, name) {
|
|
88
|
-
for (const part of (cookieHeader || "").split(";")) {
|
|
89
|
-
const separator = part.indexOf("=");
|
|
90
|
-
if (separator < 0) continue;
|
|
91
|
-
if (part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
|
|
92
|
-
}
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
95
|
-
//#endregion
|
|
96
|
-
export { ITX_APP_HEADER, ITX_CALLER_PATH_HEADER, ITX_GRANT_HEADER, ITX_PRINCIPAL_HEADER, cookieValueOf, signClaims, stampCaller, verifyAdminSecret, verifyClaims };
|
|
97
|
-
|
|
98
|
-
//# sourceMappingURL=principal.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principal.mjs","names":[],"sources":["../../src/next/principal.ts"],"sourcesContent":["// Verified attribution, the signed-claims codec (the login flow's cookie) and the admin secret's compare.\n\n/** Who is acting: a stable actor id (the control plane's user id) and, when known, an email. */\nexport type Principal = { actor: string; email?: string };\n\n/** WHO is making a call: the acting principal (null = anonymous). The one thing carried through every\n * dispatch and every sibling hop (`invoke(call, args, caller)`). Set ONLY by trusted code — the edge\n * after admission, the kernel — never by a client: the DO's `invoke` is a Workers-RPC verb, never\n * capnweb-exposed, so a client cannot supply its own `Caller`. Authority is inferred FROM the\n * principal (no separate scopes/trust field). Global contexts remain non-navigable through\n * `cd`, including calls without a principal. */\nexport type Caller = {\n principal: Principal | null;\n /** THE CONNECTION the principal acts through: the OAuth grant's id — one per connected\n * client (a Claude Code install, a dash sign-in, a personal token), the same across every call it\n * makes. Absent for the admin secret and the kernel. */\n grant?: string;\n /** The context the call ORIGINATED at — stamped by the first `cd` hop and forwarded by every later\n * one, so a relative path resolved after a hop (`repos.get('./x')` answered at the root) still\n * means the caller's `./x`. Absent until a hop. Its presence also means the complete input\n * expression was already admitted: a receiving resolver must not recheck owner-written\n * rewrites as loaded code's input. Fresh env.ITX calls never inherit this stamp. */\n path?: string;\n /** Set when the caller is LOADED CODE — a worker, a facet, a script — holding a context through\n * `env.ITX`. Under it the resolver refuses the fixed point (`itx.builtins…`) and any `cd` above\n * the caller's own context on the INPUT expression; rewrites the owner wrote are never subject. */\n app?: true;\n /** THE PLATFORM ORIGIN the caller reached the platform on (os-next platform-origin.ts) — what a\n * public URL is composed from (`itx.url`, a signed file URL). Absent for a caller with none (a\n * loaded worker's `env.ITX`, the kernel); the context then uses the last one it was reached on. */\n platformOrigin?: string | null;\n};\n/** The header the edge sets on a Request it forwards on a principal's behalf — the ingress after\n * the cookie check, a session's terminal `fetch` — and strips from every inbound Request. */\nexport const ITX_PRINCIPAL_HEADER = \"x-itx-principal\";\n/** The grant's header beside it (the caller's `grant`), set and stripped exactly where the\n * principal's is. */\nexport const ITX_GRANT_HEADER = \"x-itx-grant\";\n/** The header a loaded worker's `env.ITX.fetch` sets on the Request it forwards, so the context's\n * fetch runs the call as app code; stripped from every Request that arrives from outside. */\nexport const ITX_APP_HEADER = \"x-itx-app\";\n/** Originating context of a native fetch forwarded by a trusted context. */\nexport const ITX_CALLER_PATH_HEADER = \"x-itx-caller-path\";\n\n/** The event as the log stores it: `source.principal` and `source.grant` are the platform's — set\n * from the admitted caller, client-supplied ones dropped (an anonymous session's event carries\n * neither, the kernel's none). */\nexport function stampCaller<E extends { source?: Record<string, unknown> }>(\n event: E,\n caller: Caller,\n): E {\n const { principal: _clientPrincipal, grant: _clientGrant, ...source } = event.source || {};\n if (caller.principal) {\n const stamped: Record<string, unknown> = { ...source, principal: caller.principal };\n if (caller.grant) stamped.grant = caller.grant;\n return { ...event, source: stamped };\n }\n return Object.keys(source).length > 0\n ? { ...event, source }\n : (({ source: _dropped, ...rest }) => rest as E)(event);\n}\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst base64url = (bytes: Uint8Array): string =>\n btoa(String.fromCharCode(...bytes))\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replace(/=+$/, \"\");\nconst bytesFromBase64url = (text: string): Uint8Array<ArrayBuffer> =>\n Uint8Array.from(\n atob(\n text\n .replaceAll(\"-\", \"+\")\n .replaceAll(\"_\", \"/\")\n .padEnd(Math.ceil(text.length / 4) * 4, \"=\"),\n ),\n (c) => c.charCodeAt(0),\n );\n\nasync function hmacKey(secret: string, usage: \"sign\" | \"verify\"): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [usage],\n );\n}\n\n/** Sign JSON claims: the bounded Google login flow's cookie (identity.ts). */\nexport async function signClaims(claims: unknown, secret: string): Promise<string> {\n const payload = base64url(encoder.encode(JSON.stringify(claims)));\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await hmacKey(secret, \"sign\"),\n encoder.encode(payload),\n );\n return `${payload}.${base64url(new Uint8Array(signature))}`;\n}\n\n/** The claims of a token that is well-formed and signed with `secret` — else null (no reason: a\n * caller answers every bad token the same way). A blank secret verifies nothing. The caller checks\n * the claims' SHAPE and expiry. */\nexport async function verifyClaims(token: string, secret: string): Promise<unknown> {\n if (!secret) return null;\n const dot = token.indexOf(\".\");\n if (dot <= 0) return null;\n const payload = token.slice(0, dot);\n let signature: Uint8Array<ArrayBuffer>;\n let claims: unknown;\n try {\n signature = bytesFromBase64url(token.slice(dot + 1));\n claims = JSON.parse(decoder.decode(bytesFromBase64url(payload)));\n } catch {\n return null;\n }\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret, \"verify\"),\n signature,\n encoder.encode(payload),\n );\n return valid ? claims : null;\n}\n\nconst sha256 = async (text: string): Promise<Uint8Array> =>\n new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(text)));\n\n/** Whether two digests are the same bytes — every byte compared, no early exit, so neither a\n * matching prefix nor its length leaks by timing. */\nconst digestsEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let i = 0; i < a.length; i++) difference |= a[i]! ^ b[i]!;\n return difference === 0;\n};\n\n/** The principal the admin secret grants — `{ actor: \"admin\" }`, every project — when `candidate`\n * IS `secret` (`APP_CONFIG_ADMIN_API_SECRET`: at `authenticate({ type: \"admin-secret\" })`, as a\n * lane's bearer and on `/mcp`), else null. Both are SHA-256 hashed and the digests compared in\n * constant time. A blank secret matches nothing. */\nexport async function verifyAdminSecret(\n candidate: string,\n secret: string,\n): Promise<{ actor: \"admin\" } | null> {\n if (!secret) return null;\n const [candidateDigest, secretDigest] = await Promise.all([sha256(candidate), sha256(secret)]);\n return digestsEqual(candidateDigest, secretDigest) ? { actor: \"admin\" } : null;\n}\n\n/** The value of the cookie `name` in a `Cookie` header, or null. */\nexport function cookieValueOf(cookieHeader: string | null, name: string): string | null {\n for (const part of (cookieHeader || \"\").split(\";\")) {\n const separator = part.indexOf(\"=\");\n if (separator < 0) continue;\n if (part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();\n }\n return null;\n}\n"],"mappings":";;;AAkCA,MAAa,uBAAuB;;;AAGpC,MAAa,mBAAmB;;;AAGhC,MAAa,iBAAiB;;AAE9B,MAAa,yBAAyB;;;;AAKtC,SAAgB,YACd,OACA,QACG;CACH,MAAM,EAAE,WAAW,kBAAkB,OAAO,cAAc,GAAG,WAAW,MAAM,UAAU,CAAC;CACzF,IAAI,OAAO,WAAW;EACpB,MAAM,UAAmC;GAAE,GAAG;GAAQ,WAAW,OAAO;EAAU;EAClF,IAAI,OAAO,OAAO,QAAQ,QAAQ,OAAO;EACzC,OAAO;GAAE,GAAG;GAAO,QAAQ;EAAQ;CACrC;CACA,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAChC;EAAE,GAAG;EAAO;CAAO,MACjB,EAAE,QAAQ,UAAU,GAAG,WAAW,KAAA,CAAW,KAAK;AAC1D;AACA,MAAM,UAAU,IAAI,YAAY;AAChC,MAAM,UAAU,IAAI,YAAY;AA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AO,OAAO,CACxB,IACe,SAAS;AAC1B;AAEA,MAAM,SAAS,OAAO,SACpB,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,QAAQ,OAAO,IAAI,CAAC,CAAC;;;AAI5E,MAAM,gBAAgB,GAAe,MAA2B;CAC9D,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,IAAI,aAAa;CACjB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,cAAc,EAAE,KAAM,EAAE;CAC3D,OAAO,eAAe;AACxB;;;;;AAMA,eAAsB,kBACpB,WACA,QACoC;CACpC,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,CAAC,iBAAiB,gBAAgB,MAAM,QAAQ,IAAI,CAAC,OAAO,SAAS,GAAG,OAAO,MAAM,CAAC,CAAC;CAC7F,OAAO,aAAa,iBAAiB,YAAY,IAAI,EAAE,OAAO,QAAQ,IAAI;AAC5E;;AAGA,SAAgB,cAAc,cAA6B,MAA6B;CACtF,KAAK,MAAM,SAAS,gBAAgB,GAAA,CAAI,MAAM,GAAG,GAAG;EAClD,MAAM,YAAY,KAAK,QAAQ,GAAG;EAClC,IAAI,YAAY,GAAG;EACnB,IAAI,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK,MAAM,MAAM,OAAO,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK;CACtF;CACA,OAAO;AACT"}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
/** How projects are reached over HTTP; null ⇒ no ingress (`/api` and `/mcp` still answer). */
|
|
2
|
-
export type IngressRouting = {
|
|
3
|
-
type: "subdomains";
|
|
4
|
-
hostname: string;
|
|
5
|
-
} | {
|
|
6
|
-
type: "paths";
|
|
7
|
-
} | null;
|
|
8
|
-
/** What a request names: the project (its slug, as written — whether it EXISTS is the directory's
|
|
9
|
-
* answer), the app (null ⇒ the apex: the project's config worker answers), and the path prefix the
|
|
10
|
-
* edge strips before the app sees the URL ("" under subdomains; "/projects/<project>" or
|
|
11
|
-
* "/projects/<project>/<app>" under paths). */
|
|
12
|
-
export type ProjectAddress = {
|
|
13
|
-
project: string;
|
|
14
|
-
app: string | null;
|
|
15
|
-
basePath: string;
|
|
16
|
-
};
|
|
17
|
-
/** The project + app `url` names under `routing`, or null when it names none. Pure. */
|
|
18
|
-
export declare function projectAddressOf(routing: IngressRouting, url: URL, platformOrigin: string): ProjectAddress | null;
|
|
19
|
-
/** A CUSTOM HOSTNAME — one of a deployment's own that IS a project's apex (os-next
|
|
20
|
-
* `urls.temporaryCustomHostnames`, `{ "iterate2.com": "iterate" }`): the apex shape, `app: null`, so the
|
|
21
|
-
* project's config worker `fetch` answers exactly as it does on `<project>.<hostname>`. Null for a
|
|
22
|
-
* hostname the map does not name — the map's spelling, case and a trailing dot forgiven, no wildcard
|
|
23
|
-
* under it. Pure. */
|
|
24
|
-
export declare function customProjectHostOf(hostname: string, hostnames: Record<string, string>): {
|
|
25
|
-
app: null;
|
|
26
|
-
project: string;
|
|
27
|
-
} | null;
|
|
28
|
-
/** The URL of `app` (null ⇒ the apex, the config worker) in `project` under `routing`, at `path`
|
|
29
|
-
* (default "/", must start with "/"). Null when there is no ingress, or when the result would not
|
|
30
|
-
* parse back to the same address (a bad label; a `path` that climbs out of its app). subdomains:
|
|
31
|
-
* the protocol and port are `platformOrigin`'s (local dev is `http://localhost:8788`, so
|
|
32
|
-
* `http://<app>--<project>.localhost:8788/…`); paths: `<platformOrigin>/projects/<project>[/<app>]<path>`. Pure. */
|
|
33
|
-
export declare function projectUrlOf(routing: IngressRouting, platformOrigin: string, target: {
|
|
34
|
-
project: string;
|
|
35
|
-
app?: string | null;
|
|
36
|
-
path?: string;
|
|
37
|
-
}): URL | null;
|