@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md +7 -0
- package/LICENSE +201 -0
- package/README.md +233 -2
- package/bin/ui-kit.js +12 -0
- package/dist/alchemy/app.d.ts +34 -0
- package/dist/alchemy/app.js +88 -0
- package/dist/alchemy/index.d.ts +11 -0
- package/dist/alchemy/index.js +11 -0
- package/dist/alchemy/live-rooms.d.ts +21 -0
- package/dist/alchemy/live-rooms.js +31 -0
- package/dist/alchemy/migrations.d.ts +28 -0
- package/dist/alchemy/migrations.js +56 -0
- package/dist/alchemy/stage.d.ts +20 -0
- package/dist/alchemy/stage.js +20 -0
- package/dist/alchemy/wrangler-config.d.ts +76 -0
- package/dist/alchemy/wrangler-config.js +82 -0
- package/dist/build/app-modules.d.ts +11 -0
- package/dist/build/app-modules.js +40 -0
- package/dist/build/check.d.ts +4 -0
- package/dist/build/check.js +170 -0
- package/dist/build/cli.d.ts +1 -0
- package/dist/build/cli.js +79 -0
- package/dist/build/feature.d.ts +8 -0
- package/dist/build/feature.js +24 -0
- package/dist/build/index.d.ts +13 -0
- package/dist/build/index.js +13 -0
- package/dist/build/measure-cpu.d.ts +2 -0
- package/dist/build/measure-cpu.js +196 -0
- package/dist/build/prerender.d.ts +5 -0
- package/dist/build/prerender.js +109 -0
- package/dist/build/preview.d.ts +7 -0
- package/dist/build/preview.js +41 -0
- package/dist/build/seo-files.d.ts +27 -0
- package/dist/build/seo-files.js +24 -0
- package/dist/client/head-swap.d.ts +45 -0
- package/dist/client/head-swap.js +183 -0
- package/dist/client/hydration-pass.d.ts +56 -0
- package/dist/client/hydration-pass.js +186 -0
- package/dist/client/hydration-reset.d.ts +82 -0
- package/dist/client/hydration-reset.js +154 -0
- package/dist/client/index.d.ts +37 -0
- package/dist/client/index.js +65 -0
- package/dist/client/nav-client.d.ts +35 -0
- package/dist/client/nav-client.js +371 -0
- package/dist/live/collab/doc-provider.d.ts +74 -0
- package/dist/live/collab/doc-provider.js +412 -0
- package/dist/live/collab/index.d.ts +51 -0
- package/dist/live/collab/index.jsx +142 -0
- package/dist/live/collab-status.d.ts +25 -0
- package/dist/live/collab-status.js +17 -0
- package/dist/live/cursors/cursor-engine.d.ts +57 -0
- package/dist/live/cursors/cursor-engine.js +243 -0
- package/dist/live/cursors/index.d.ts +46 -0
- package/dist/live/cursors/index.jsx +110 -0
- package/dist/live/declaration.d.ts +113 -0
- package/dist/live/declaration.js +94 -0
- package/dist/live/index.d.ts +8 -0
- package/dist/live/index.js +8 -0
- package/dist/live/protocol.d.ts +224 -0
- package/dist/live/protocol.js +272 -0
- package/dist/live/server/doc-store.d.ts +68 -0
- package/dist/live/server/doc-store.js +187 -0
- package/dist/live/server/index.d.ts +60 -0
- package/dist/live/server/index.js +77 -0
- package/dist/live/server/room-presence.d.ts +24 -0
- package/dist/live/server/room-presence.js +123 -0
- package/dist/live/server/room-sockets.d.ts +65 -0
- package/dist/live/server/room-sockets.js +97 -0
- package/dist/live/server/room.d.ts +20 -0
- package/dist/live/server/room.js +348 -0
- package/dist/live/server/route.d.ts +56 -0
- package/dist/live/server/route.js +159 -0
- package/dist/live/server/types.d.ts +163 -0
- package/dist/live/server/types.js +2 -0
- package/dist/logic/agent-actions.d.ts +133 -0
- package/dist/logic/agent-actions.js +150 -0
- package/dist/logic/command-types.d.ts +53 -0
- package/dist/logic/command-types.js +0 -0
- package/dist/logic/dev.d.ts +9 -0
- package/dist/logic/dev.js +10 -0
- package/dist/logic/draft-rebase.d.ts +59 -0
- package/dist/logic/draft-rebase.js +71 -0
- package/dist/logic/form-state.d.ts +105 -0
- package/dist/logic/form-state.js +93 -0
- package/dist/logic/head.d.ts +145 -0
- package/dist/logic/head.js +140 -0
- package/dist/logic/index.d.ts +27 -0
- package/dist/logic/index.js +25 -0
- package/dist/logic/island-def.d.ts +89 -0
- package/dist/logic/island-def.js +59 -0
- package/dist/logic/kit-commands.d.ts +104 -0
- package/dist/logic/kit-commands.js +72 -0
- package/dist/logic/kit-errors.d.ts +25 -0
- package/dist/logic/kit-errors.js +6 -0
- package/dist/logic/listen.d.ts +99 -0
- package/dist/logic/listen.js +92 -0
- package/dist/logic/mutation-def.d.ts +65 -0
- package/dist/logic/mutation-def.js +43 -0
- package/dist/logic/navigation-data.d.ts +50 -0
- package/dist/logic/navigation-data.js +55 -0
- package/dist/logic/navigation-policy.d.ts +74 -0
- package/dist/logic/navigation-policy.js +127 -0
- package/dist/logic/page-model-def.d.ts +108 -0
- package/dist/logic/page-model-def.js +31 -0
- package/dist/logic/path.d.ts +31 -0
- package/dist/logic/path.js +48 -0
- package/dist/logic/query-def.d.ts +56 -0
- package/dist/logic/query-def.js +37 -0
- package/dist/logic/query-key.d.ts +24 -0
- package/dist/logic/query-key.js +35 -0
- package/dist/logic/query-types.d.ts +28 -0
- package/dist/logic/query-types.js +2 -0
- package/dist/logic/resources.d.ts +163 -0
- package/dist/logic/resources.js +62 -0
- package/dist/logic/result.d.ts +30 -0
- package/dist/logic/result.js +23 -0
- package/dist/logic/route-model.d.ts +139 -0
- package/dist/logic/route-model.js +207 -0
- package/dist/logic/route-params.d.ts +80 -0
- package/dist/logic/route-params.js +114 -0
- package/dist/logic/route-table.d.ts +308 -0
- package/dist/logic/route-table.js +206 -0
- package/dist/logic/seo.d.ts +61 -0
- package/dist/logic/seo.js +101 -0
- package/dist/logic/site.d.ts +12 -0
- package/dist/logic/site.js +0 -0
- package/dist/logic/subscriptions.d.ts +177 -0
- package/dist/logic/subscriptions.js +152 -0
- package/dist/render/index.d.ts +32 -0
- package/dist/render/index.js +52 -0
- package/dist/runtime/island-wake.d.ts +38 -0
- package/dist/runtime/island-wake.js +147 -0
- package/dist/runtime/query-scope.d.ts +224 -0
- package/dist/runtime/query-scope.js +222 -0
- package/dist/runtime/room-hub.d.ts +107 -0
- package/dist/runtime/room-hub.js +307 -0
- package/dist/runtime/subscription-runner.d.ts +71 -0
- package/dist/runtime/subscription-runner.js +240 -0
- package/dist/server/bindings.d.ts +41 -0
- package/dist/server/bindings.js +74 -0
- package/dist/server/browser.d.ts +9 -0
- package/dist/server/browser.js +9 -0
- package/dist/server/edge-cache.d.ts +28 -0
- package/dist/server/edge-cache.js +35 -0
- package/dist/server/errors.d.ts +45 -0
- package/dist/server/errors.js +36 -0
- package/dist/server/form-actions-setup.d.ts +1 -0
- package/dist/server/form-actions-setup.js +15 -0
- package/dist/server/form-actions.d.ts +121 -0
- package/dist/server/form-actions.js +211 -0
- package/dist/server/index.d.ts +36 -0
- package/dist/server/index.js +35 -0
- package/dist/server/inputs.d.ts +45 -0
- package/dist/server/inputs.js +77 -0
- package/dist/server/rate-limit.d.ts +29 -0
- package/dist/server/rate-limit.js +32 -0
- package/dist/server/read-cache.d.ts +74 -0
- package/dist/server/read-cache.js +58 -0
- package/dist/server/request-info.d.ts +17 -0
- package/dist/server/request-info.js +11 -0
- package/dist/server/request.d.ts +52 -0
- package/dist/server/request.js +73 -0
- package/dist/server/response-cookies.d.ts +23 -0
- package/dist/server/response-cookies.js +24 -0
- package/dist/server/run-effect.d.ts +42 -0
- package/dist/server/run-effect.js +92 -0
- package/dist/server/run.d.ts +63 -0
- package/dist/server/run.js +66 -0
- package/dist/server/session.d.ts +125 -0
- package/dist/server/session.js +247 -0
- package/dist/test/fake-bindings.d.ts +32 -0
- package/dist/test/fake-bindings.js +108 -0
- package/dist/test/fake-room.d.ts +66 -0
- package/dist/test/fake-room.js +216 -0
- package/dist/test/index.d.ts +19 -0
- package/dist/test/index.js +44 -0
- package/dist/test/probe.d.ts +11 -0
- package/dist/test/probe.js +11 -0
- package/dist/test/solid-jsx.d.ts +23 -0
- package/dist/test/solid-jsx.js +28 -0
- package/dist/test/solid-preload.d.ts +1 -0
- package/dist/test/solid-preload.js +29 -0
- package/dist/ui/code-editor/index.d.ts +21 -0
- package/dist/ui/code-editor/index.jsx +286 -0
- package/dist/ui/collab-text/index.d.ts +29 -0
- package/dist/ui/collab-text/index.jsx +96 -0
- package/dist/ui/components/controls.d.ts +69 -0
- package/dist/ui/components/controls.jsx +81 -0
- package/dist/ui/components/feedback.d.ts +26 -0
- package/dist/ui/components/feedback.jsx +80 -0
- package/dist/ui/components/layout.d.ts +74 -0
- package/dist/ui/components/layout.jsx +146 -0
- package/dist/ui/components/lists.d.ts +69 -0
- package/dist/ui/components/lists.jsx +133 -0
- package/dist/ui/components/navigation.d.ts +73 -0
- package/dist/ui/components/navigation.jsx +112 -0
- package/dist/ui/components/text.d.ts +34 -0
- package/dist/ui/components/text.jsx +163 -0
- package/dist/ui/index.d.ts +7 -0
- package/dist/ui/index.js +7 -0
- package/dist/ui/jsx-runtime.d.ts +19 -0
- package/dist/ui/jsx-runtime.js +0 -0
- package/dist/ui/list-keys.d.ts +31 -0
- package/dist/ui/list-keys.js +45 -0
- package/dist/ui/styles/base.css +38 -0
- package/dist/ui/styles/components.css +608 -0
- package/dist/ui/styles/tokens.css +27 -0
- package/dist/ui/styles/transitions.css +23 -0
- package/dist/ui/styles/workbench.css +428 -0
- package/dist/ui/styles.css +9 -0
- package/dist/view/agent-actions-view.d.ts +30 -0
- package/dist/view/agent-actions-view.js +27 -0
- package/dist/view/agent-surface.d.ts +42 -0
- package/dist/view/agent-surface.js +123 -0
- package/dist/view/app-scope.d.ts +51 -0
- package/dist/view/app-scope.js +75 -0
- package/dist/view/boundary.d.ts +18 -0
- package/dist/view/boundary.jsx +26 -0
- package/dist/view/command-runner.d.ts +16 -0
- package/dist/view/command-runner.js +245 -0
- package/dist/view/form.d.ts +82 -0
- package/dist/view/form.jsx +109 -0
- package/dist/view/head-view.d.ts +31 -0
- package/dist/view/head-view.js +46 -0
- package/dist/view/index.d.ts +41 -0
- package/dist/view/index.js +40 -0
- package/dist/view/island-root.d.ts +30 -0
- package/dist/view/island-root.js +36 -0
- package/dist/view/island.d.ts +102 -0
- package/dist/view/island.jsx +154 -0
- package/dist/view/match.d.ts +41 -0
- package/dist/view/match.js +111 -0
- package/dist/view/model.d.ts +92 -0
- package/dist/view/model.js +162 -0
- package/dist/view/navigation-head.d.ts +29 -0
- package/dist/view/navigation-head.jsx +38 -0
- package/dist/view/page-model.d.ts +46 -0
- package/dist/view/page-model.js +146 -0
- package/dist/view/query-effects.d.ts +87 -0
- package/dist/view/query-effects.js +147 -0
- package/dist/view/query-ok.d.ts +45 -0
- package/dist/view/query-ok.js +96 -0
- package/dist/view/query.d.ts +115 -0
- package/dist/view/query.jsx +179 -0
- package/dist/view/result-view.d.ts +14 -0
- package/dist/view/result-view.jsx +15 -0
- package/dist/view/route-pages.d.ts +43 -0
- package/dist/view/route-pages.js +59 -0
- package/dist/view/router.d.ts +44 -0
- package/dist/view/router.js +123 -0
- package/dist/vite/dev-middleware.d.ts +12 -0
- package/dist/vite/dev-middleware.js +39 -0
- package/dist/vite/dev-objects.d.ts +25 -0
- package/dist/vite/dev-objects.js +127 -0
- package/dist/vite/dev-platform.d.ts +19 -0
- package/dist/vite/dev-platform.js +77 -0
- package/dist/vite/dev-seo-files.d.ts +11 -0
- package/dist/vite/dev-seo-files.js +40 -0
- package/dist/vite/index.d.ts +53 -0
- package/dist/vite/index.js +148 -0
- package/dist/vite/local-config.d.ts +34 -0
- package/dist/vite/local-config.js +72 -0
- package/dist/vite/worker-build.d.ts +24 -0
- package/dist/vite/worker-build.js +84 -0
- package/dist/worker/create-worker.d.ts +52 -0
- package/dist/worker/create-worker.js +90 -0
- package/dist/worker/index.d.ts +12 -0
- package/dist/worker/index.js +12 -0
- package/dist/worker/page-routes.d.ts +88 -0
- package/dist/worker/page-routes.js +100 -0
- package/dist/worker/page-status.d.ts +41 -0
- package/dist/worker/page-status.js +23 -0
- package/dist/worker/request-prelude.d.ts +69 -0
- package/dist/worker/request-prelude.js +107 -0
- package/dist/worker/security.d.ts +76 -0
- package/dist/worker/security.js +137 -0
- package/dist/worker/server-app.d.ts +54 -0
- package/dist/worker/server-app.js +76 -0
- package/guards/browser-only.js +5 -0
- package/guards/node-only.js +6 -0
- package/guards/server-only.js +5 -0
- package/migrations/0001-sessions.sql +22 -0
- package/package.json +233 -5
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ok } from '../logic/result.js';
|
|
2
|
+
/** Header values for a cache policy (pure; `runRead` applies them). */
|
|
3
|
+
export const CACHE_CONTROL = {
|
|
4
|
+
/** Personal or session-dependent: nobody but this browser, and not even stored there. */
|
|
5
|
+
PRIVATE: 'private, no-store',
|
|
6
|
+
/** Errors and anything else that must not be stored anywhere. */
|
|
7
|
+
NO_STORE: 'no-store',
|
|
8
|
+
/** Browsers keep shared reads but revalidate (at the edge) every time. */
|
|
9
|
+
BROWSER_REVALIDATE: 'no-cache',
|
|
10
|
+
};
|
|
11
|
+
const CACHE_TAG = /^[A-Za-z0-9:_./-]{1,128}$/;
|
|
12
|
+
/**
|
|
13
|
+
* The response headers for one GET read's outcome.
|
|
14
|
+
*
|
|
15
|
+
* Rules, in order:
|
|
16
|
+
* 1. the read touched the session (`sessionRead`): `private, no-store`,
|
|
17
|
+
* whatever the policy says (a session read is never shared-cached);
|
|
18
|
+
* 2. `Private` policy: `private, no-store`;
|
|
19
|
+
* 3. an `Err` outcome: `no-store` (errors aren't cached);
|
|
20
|
+
* 4. `Shared` + `Ok`: `Cache-Control: no-cache`, `CDN-Cache-Control:
|
|
21
|
+
* public, max-age=N, stale-while-revalidate=M`, `Cache-Tag: a,b`.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* readCacheHeaders(policy, ok(plan), { sessionRead: false });
|
|
26
|
+
* // { "Cache-Control": "no-cache", "CDN-Cache-Control": "public, max-age=10, stale-while-revalidate=60", "Cache-Tag": "plan,plan:voltar-main" }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export function readCacheHeaders(policy, result, read) {
|
|
30
|
+
if (read.sessionRead || policy._tag === 'Private') {
|
|
31
|
+
return { 'Cache-Control': CACHE_CONTROL.PRIVATE };
|
|
32
|
+
}
|
|
33
|
+
if (result._tag === 'Err')
|
|
34
|
+
return { 'Cache-Control': CACHE_CONTROL.NO_STORE };
|
|
35
|
+
const tags = policy.tags(result.value).filter((tag) => CACHE_TAG.test(tag));
|
|
36
|
+
return {
|
|
37
|
+
'Cache-Control': CACHE_CONTROL.BROWSER_REVALIDATE,
|
|
38
|
+
'CDN-Cache-Control': `public, max-age=${policy.maxAgeSec}, stale-while-revalidate=${policy.staleWhileRevalidateSec}`,
|
|
39
|
+
...(tags.length > 0 ? { 'Cache-Tag': tags.join(',') } : {}),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A `Shared` policy: edge-cached `maxAgeSec`, served stale up to
|
|
44
|
+
* `staleWhileRevalidateSec` while it refreshes, purged by `tags`.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* export const READ_CACHE = {
|
|
49
|
+
* loadCharacter: sharedRead<Character>(60, 300, (c) => [`character:${c.id}`]),
|
|
50
|
+
* loadPlan: PRIVATE_READ,
|
|
51
|
+
* } as const
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export function sharedRead(maxAgeSec, staleWhileRevalidateSec, tags) {
|
|
55
|
+
return { _tag: 'Shared', maxAgeSec, staleWhileRevalidateSec, tags };
|
|
56
|
+
}
|
|
57
|
+
/** The `Private` policy: never shared-cached. */
|
|
58
|
+
export const PRIVATE_READ = { _tag: 'Private' };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Context, Layer } from 'effect';
|
|
2
|
+
interface RequestInfoShape {
|
|
3
|
+
/** The request URL (`http://localhost/` outside a request: a cron, a probe). */
|
|
4
|
+
readonly url: URL;
|
|
5
|
+
/** `CF-Connecting-IP`; absent under `vite dev` and outside a request. */
|
|
6
|
+
readonly client_ip: string | undefined;
|
|
7
|
+
}
|
|
8
|
+
declare const RequestInfo_base: Context.ServiceClass<RequestInfo, "@alecsibilia/ui-kit/server/RequestInfo", RequestInfoShape>;
|
|
9
|
+
/**
|
|
10
|
+
* What a program may know about the request it serves, provided per call
|
|
11
|
+
* (rate limit keys, absolute URLs). Never the raw request: programs stay
|
|
12
|
+
* testable with a plain value.
|
|
13
|
+
*/
|
|
14
|
+
export declare class RequestInfo extends RequestInfo_base {
|
|
15
|
+
static layer(info: RequestInfoShape): Layer.Layer<RequestInfo>;
|
|
16
|
+
}
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Context, Layer } from 'effect';
|
|
2
|
+
/**
|
|
3
|
+
* What a program may know about the request it serves, provided per call
|
|
4
|
+
* (rate limit keys, absolute URLs). Never the raw request: programs stay
|
|
5
|
+
* testable with a plain value.
|
|
6
|
+
*/
|
|
7
|
+
export class RequestInfo extends Context.Service()('@alecsibilia/ui-kit/server/RequestInfo') {
|
|
8
|
+
static layer(info) {
|
|
9
|
+
return Layer.succeed(RequestInfo, info);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The current request, for app server code (which may not import Solid):
|
|
3
|
+
* its locals, URL and headers, and response headers on a returned value.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The current request's `locals` bag, where the Worker entry puts the
|
|
7
|
+
* request's `env` (bindings) and `ctx` (`handleRequest(request, { event: {
|
|
8
|
+
* locals: { env, ctx } } })`). Server functions read it per call to build
|
|
9
|
+
* their Effect Layer, so no Layer holding bindings lives at module level.
|
|
10
|
+
*
|
|
11
|
+
* Throws outside a request scope (a module top level, a test that calls a
|
|
12
|
+
* server function directly): there are no bindings to hand out there.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* const env = parseEnv(requestLocals().env);
|
|
17
|
+
* return runEffectResult(program, makeLayer(env));
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare function requestLocals(): Readonly<Record<string, unknown>>;
|
|
21
|
+
/** Cookie header parsing and `Set-Cookie` serialization (Solid's). */
|
|
22
|
+
export { parseCookieHeader, serializeCookie, type CookieOptions, } from '@solidjs/web';
|
|
23
|
+
/**
|
|
24
|
+
* The current request's URL (outside a request scope, `http://localhost/`).
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* sessionCookie(requestUrl(), token);
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function requestUrl(): URL;
|
|
32
|
+
/**
|
|
33
|
+
* One header of the current request (`undefined` outside a request scope or
|
|
34
|
+
* when absent). For app server code that may not import Solid.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* const ip = requestHeader("CF-Connecting-IP") ?? "local";
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export declare function requestHeader(name: string): string | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* A server function's return value with response headers attached (Solid's
|
|
44
|
+
* `respond`): callers (scripted, in-process, no-JS form posts) still get the
|
|
45
|
+
* value; the HTTP response carries the headers.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* return withResponseHeaders(result, [["Cache-Control", "private, no-store"]]);
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function withResponseHeaders<T>(value: T, headers: readonly (readonly [string, string])[]): T;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { getRequestEvent, respond } from '@solidjs/web';
|
|
2
|
+
import { Effect, Layer } from 'effect';
|
|
3
|
+
/**
|
|
4
|
+
* The current request, for app server code (which may not import Solid):
|
|
5
|
+
* its locals, URL and headers, and response headers on a returned value.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* The current request's `locals` bag, where the Worker entry puts the
|
|
9
|
+
* request's `env` (bindings) and `ctx` (`handleRequest(request, { event: {
|
|
10
|
+
* locals: { env, ctx } } })`). Server functions read it per call to build
|
|
11
|
+
* their Effect Layer, so no Layer holding bindings lives at module level.
|
|
12
|
+
*
|
|
13
|
+
* Throws outside a request scope (a module top level, a test that calls a
|
|
14
|
+
* server function directly): there are no bindings to hand out there.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const env = parseEnv(requestLocals().env);
|
|
19
|
+
* return runEffectResult(program, makeLayer(env));
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function requestLocals() {
|
|
23
|
+
const event = getRequestEvent();
|
|
24
|
+
if (!event) {
|
|
25
|
+
throw new Error('requestLocals() called outside a request scope');
|
|
26
|
+
}
|
|
27
|
+
return event.locals;
|
|
28
|
+
}
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Request / response helpers for app server code (which may not import Solid).
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
/** Cookie header parsing and `Set-Cookie` serialization (Solid's). */
|
|
33
|
+
export { parseCookieHeader, serializeCookie, } from '@solidjs/web';
|
|
34
|
+
/**
|
|
35
|
+
* The current request's URL (outside a request scope, `http://localhost/`).
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* sessionCookie(requestUrl(), token);
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function requestUrl() {
|
|
43
|
+
return new URL(getRequestEvent()?.request.url ?? 'http://localhost/');
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One header of the current request (`undefined` outside a request scope or
|
|
47
|
+
* when absent). For app server code that may not import Solid.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const ip = requestHeader("CF-Connecting-IP") ?? "local";
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export function requestHeader(name) {
|
|
55
|
+
return getRequestEvent()?.request.headers.get(name) ?? undefined;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A server function's return value with response headers attached (Solid's
|
|
59
|
+
* `respond`): callers (scripted, in-process, no-JS form posts) still get the
|
|
60
|
+
* value; the HTTP response carries the headers.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* return withResponseHeaders(result, [["Cache-Control", "private, no-store"]]);
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export function withResponseHeaders(value, headers) {
|
|
68
|
+
if (headers.length === 0)
|
|
69
|
+
return value;
|
|
70
|
+
return respond(value, {
|
|
71
|
+
headers: headers.map(([name, v]) => [name, v]),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Context, Effect, Layer } from 'effect';
|
|
2
|
+
interface ResponseCookiesShape {
|
|
3
|
+
/** This call's request URL (cookie `Secure` / name depend on it). */
|
|
4
|
+
readonly requestUrl: URL;
|
|
5
|
+
/** Adds a `Set-Cookie` to this call's response. */
|
|
6
|
+
readonly set: (cookie: string) => Effect.Effect<void>;
|
|
7
|
+
}
|
|
8
|
+
declare const ResponseCookies_base: Context.ServiceClass<ResponseCookies, "@alecsibilia/ui-kit/server/ResponseCookies", ResponseCookiesShape>;
|
|
9
|
+
/**
|
|
10
|
+
* Cookies a server function sets on its own response (sign-in, sign-out),
|
|
11
|
+
* provided per call. The runner (`createRunner`) collects them and returns
|
|
12
|
+
* the result through Solid's `respond(value, { headers })`, so they ride on
|
|
13
|
+
* a scripted call's response and on a no-JS form post's 303 alike.
|
|
14
|
+
*/
|
|
15
|
+
export declare class ResponseCookies extends ResponseCookies_base {
|
|
16
|
+
/** A layer that appends every cookie to `sink`. */
|
|
17
|
+
static layer(requestUrl: URL, sink: string[]): Layer.Layer<ResponseCookies>;
|
|
18
|
+
/** The service value for one call. */
|
|
19
|
+
static forCall(requestUrl: URL, sink: string[]): ResponseCookiesShape;
|
|
20
|
+
}
|
|
21
|
+
/** Response headers carrying `cookies` (what the runner attaches to a call's response). */
|
|
22
|
+
export declare function cookieHeaders(cookies: readonly string[]): [string, string][];
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Context, Effect, Layer } from 'effect';
|
|
2
|
+
/**
|
|
3
|
+
* Cookies a server function sets on its own response (sign-in, sign-out),
|
|
4
|
+
* provided per call. The runner (`createRunner`) collects them and returns
|
|
5
|
+
* the result through Solid's `respond(value, { headers })`, so they ride on
|
|
6
|
+
* a scripted call's response and on a no-JS form post's 303 alike.
|
|
7
|
+
*/
|
|
8
|
+
export class ResponseCookies extends Context.Service()('@alecsibilia/ui-kit/server/ResponseCookies') {
|
|
9
|
+
/** A layer that appends every cookie to `sink`. */
|
|
10
|
+
static layer(requestUrl, sink) {
|
|
11
|
+
return Layer.succeed(ResponseCookies, ResponseCookies.forCall(requestUrl, sink));
|
|
12
|
+
}
|
|
13
|
+
/** The service value for one call. */
|
|
14
|
+
static forCall(requestUrl, sink) {
|
|
15
|
+
return {
|
|
16
|
+
requestUrl,
|
|
17
|
+
set: (cookie) => Effect.sync(() => void sink.push(cookie)),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Response headers carrying `cookies` (what the runner attaches to a call's response). */
|
|
22
|
+
export function cookieHeaders(cookies) {
|
|
23
|
+
return cookies.map((cookie) => ['Set-Cookie', cookie]);
|
|
24
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Effect, Layer } from 'effect';
|
|
2
|
+
import { type Result, type Tagged } from '../logic/result.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Runs Effect programs for server functions and turns their outcome into the
|
|
5
|
+
* plain `Result` that crosses the wire.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Converts a tagged error (including Effect `Schema.TaggedError` class instances)
|
|
9
|
+
* into a plain, JSON/seroval-serializable tagged object so it crosses Solid's
|
|
10
|
+
* `"use server"` boundary with zero Effect runtime in the browser.
|
|
11
|
+
*/
|
|
12
|
+
export type PlainTaggedError<E extends Tagged> = E extends Tagged ? {
|
|
13
|
+
readonly [K in keyof E as K extends symbol | `~${string}` | 'name' | 'stack' | 'cause' | 'toJSON' | 'toString' ? never : E[K] extends (...args: never[]) => unknown ? never : K]: E[K];
|
|
14
|
+
} & {
|
|
15
|
+
readonly _tag: E['_tag'];
|
|
16
|
+
} : never;
|
|
17
|
+
/** Message carried by the sanitized error thrown for unexpected defects. */
|
|
18
|
+
export declare const UNEXPECTED_SERVER_ERROR_MESSAGE = "Unexpected server error";
|
|
19
|
+
/**
|
|
20
|
+
* Runs an Effect 4.2 program with the provided Layer, catches expected typed
|
|
21
|
+
* failures (`_tag`), and returns a plain JSON-serializable `Result<A, E>`.
|
|
22
|
+
* Expected failures are reduced to `_tag`, `message` and their schema-declared
|
|
23
|
+
* fields (see `toPlainTaggedError`) so no stack, cause or Effect internals
|
|
24
|
+
* cross the `"use server"` boundary.
|
|
25
|
+
*
|
|
26
|
+
* `layer` is meant to be built once at module level (it holds no
|
|
27
|
+
* per-request value); `requestLayer`, when given, is the one thing built
|
|
28
|
+
* per call, typically `Layer.succeed(Bindings, env)` for this request's
|
|
29
|
+
* Worker bindings, which `layer`'s services read when they run.
|
|
30
|
+
*
|
|
31
|
+
* Unexpected defects / interruptions are logged server-side with the full
|
|
32
|
+
* cause, then rethrown as a fresh `Error(UNEXPECTED_SERVER_ERROR_MESSAGE)`
|
|
33
|
+
* with no stack details or cause attached, so `<Query>` shows its
|
|
34
|
+
* `{ _tag: "Unexpected" }` error without leaking server internals.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* const result = await runEffectResult(getPlanProgram("x"), AppLayer, Bindings.layer(env));
|
|
39
|
+
* // { _tag: "Err", error: { _tag: "PlanNotFound", planId: "x", message: "..." } }
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function runEffectResult<A, E extends Tagged, R, R2 = never>(effect: Effect.Effect<A, E, R | R2>, layer: Layer.Layer<R>, requestLayer?: Layer.Layer<R2>): Promise<Result<A, PlainTaggedError<E>>>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { Cause, Effect, Exit, Layer, Option } from 'effect';
|
|
2
|
+
import { err, ok } from '../logic/result.js';
|
|
3
|
+
const OMITTED_ERROR_KEYS = new Set([
|
|
4
|
+
'name',
|
|
5
|
+
'stack',
|
|
6
|
+
'cause',
|
|
7
|
+
'toJSON',
|
|
8
|
+
'toString',
|
|
9
|
+
]);
|
|
10
|
+
function isForwardableKey(key) {
|
|
11
|
+
return !OMITTED_ERROR_KEYS.has(key) && !key.startsWith('~');
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Field names declared by an Effect `Schema.TaggedError` class (exposed as the
|
|
15
|
+
* static `fields` record), or `undefined` for plain tagged objects.
|
|
16
|
+
*/
|
|
17
|
+
function declaredFieldNames(error) {
|
|
18
|
+
const ctor = error.constructor;
|
|
19
|
+
const fields = ctor?.fields;
|
|
20
|
+
return fields !== null && typeof fields === 'object'
|
|
21
|
+
? Object.keys(fields)
|
|
22
|
+
: undefined;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Copies ONLY `_tag`, `message`, and the schema-declared fields of a tagged
|
|
26
|
+
* error into a fresh plain object. Never forwards `stack`, `cause`, `name`,
|
|
27
|
+
* symbol keys, Effect internals (keys starting with `~`), engine extras (`line`, `sourceURL`, ...)
|
|
28
|
+
* or functions. Plain (non-class) tagged objects fall back to their own
|
|
29
|
+
* enumerable keys with the same exclusions.
|
|
30
|
+
*/
|
|
31
|
+
function toPlainTaggedError(error) {
|
|
32
|
+
const source = error;
|
|
33
|
+
const plain = { _tag: error._tag };
|
|
34
|
+
const keys = declaredFieldNames(error) ?? Object.keys(error);
|
|
35
|
+
for (const key of keys) {
|
|
36
|
+
if (key === '_tag' || !isForwardableKey(key))
|
|
37
|
+
continue;
|
|
38
|
+
const val = source[key];
|
|
39
|
+
if (val !== undefined && typeof val !== 'function') {
|
|
40
|
+
plain[key] = val;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const maybeMessage = source.message;
|
|
44
|
+
if (typeof maybeMessage === 'string' && maybeMessage.length > 0) {
|
|
45
|
+
plain.message = maybeMessage;
|
|
46
|
+
}
|
|
47
|
+
return plain;
|
|
48
|
+
}
|
|
49
|
+
/** Message carried by the sanitized error thrown for unexpected defects. */
|
|
50
|
+
export const UNEXPECTED_SERVER_ERROR_MESSAGE = 'Unexpected server error';
|
|
51
|
+
/**
|
|
52
|
+
* Runs an Effect 4.2 program with the provided Layer, catches expected typed
|
|
53
|
+
* failures (`_tag`), and returns a plain JSON-serializable `Result<A, E>`.
|
|
54
|
+
* Expected failures are reduced to `_tag`, `message` and their schema-declared
|
|
55
|
+
* fields (see `toPlainTaggedError`) so no stack, cause or Effect internals
|
|
56
|
+
* cross the `"use server"` boundary.
|
|
57
|
+
*
|
|
58
|
+
* `layer` is meant to be built once at module level (it holds no
|
|
59
|
+
* per-request value); `requestLayer`, when given, is the one thing built
|
|
60
|
+
* per call, typically `Layer.succeed(Bindings, env)` for this request's
|
|
61
|
+
* Worker bindings, which `layer`'s services read when they run.
|
|
62
|
+
*
|
|
63
|
+
* Unexpected defects / interruptions are logged server-side with the full
|
|
64
|
+
* cause, then rethrown as a fresh `Error(UNEXPECTED_SERVER_ERROR_MESSAGE)`
|
|
65
|
+
* with no stack details or cause attached, so `<Query>` shows its
|
|
66
|
+
* `{ _tag: "Unexpected" }` error without leaking server internals.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const result = await runEffectResult(getPlanProgram("x"), AppLayer, Bindings.layer(env));
|
|
71
|
+
* // { _tag: "Err", error: { _tag: "PlanNotFound", planId: "x", message: "..." } }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export async function runEffectResult(effect, layer, requestLayer) {
|
|
75
|
+
const withServices = Effect.provide(effect, layer);
|
|
76
|
+
const provided = (requestLayer === undefined
|
|
77
|
+
? withServices
|
|
78
|
+
: Effect.provide(withServices, requestLayer));
|
|
79
|
+
const exit = await Effect.runPromiseExit(provided);
|
|
80
|
+
if (Exit.isSuccess(exit)) {
|
|
81
|
+
return ok(exit.value);
|
|
82
|
+
}
|
|
83
|
+
const failureOpt = Cause.findErrorOption(exit.cause);
|
|
84
|
+
if (Option.isSome(failureOpt)) {
|
|
85
|
+
return err(toPlainTaggedError(failureOpt.value));
|
|
86
|
+
}
|
|
87
|
+
console.error('[runEffectResult] Unexpected defect:\n' + Cause.pretty(exit.cause));
|
|
88
|
+
const sanitized = new Error(UNEXPECTED_SERVER_ERROR_MESSAGE);
|
|
89
|
+
// Drop server stack frames so they can't be serialized to the browser.
|
|
90
|
+
sanitized.stack = `Error: ${UNEXPECTED_SERVER_ERROR_MESSAGE}`;
|
|
91
|
+
throw sanitized;
|
|
92
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Layer, type Effect } from 'effect';
|
|
2
|
+
import { Bindings } from './bindings.ts';
|
|
3
|
+
import { EdgeCache } from './edge-cache.ts';
|
|
4
|
+
import { type ReadCachePolicy } from './read-cache.ts';
|
|
5
|
+
import { RequestInfo } from './request-info.ts';
|
|
6
|
+
import { ResponseCookies } from './response-cookies.ts';
|
|
7
|
+
import { type PlainTaggedError } from './run-effect.ts';
|
|
8
|
+
import { Session } from './session.ts';
|
|
9
|
+
import type { ResourcesDecl } from '../logic/resources.ts';
|
|
10
|
+
import type { Result, Tagged } from '../logic/result.ts';
|
|
11
|
+
/** The services the kit provides to every call (on top of the app's layer). */
|
|
12
|
+
export type CallServices = Bindings | Session | EdgeCache | ResponseCookies | RequestInfo;
|
|
13
|
+
/** What one call learned while it ran (per call, never module-level). */
|
|
14
|
+
export interface CallRecord {
|
|
15
|
+
sessionRead: boolean;
|
|
16
|
+
readonly cookies: string[];
|
|
17
|
+
}
|
|
18
|
+
/** What a call's services are built from (tests pass fakes here). */
|
|
19
|
+
export interface CallInputs {
|
|
20
|
+
/** The Worker `env` (each binding checked on use). */
|
|
21
|
+
readonly env: unknown;
|
|
22
|
+
/** The Worker `ExecutionContext` (`ctx.cache` purges Workers Cache). */
|
|
23
|
+
readonly ctx?: unknown;
|
|
24
|
+
/** `locals.session`: a session or a lazy lookup (anything else is `SignedOut`). */
|
|
25
|
+
readonly session?: unknown;
|
|
26
|
+
readonly requestUrl: URL;
|
|
27
|
+
/** `CF-Connecting-IP` (absent under `vite dev`). */
|
|
28
|
+
readonly clientIp?: string;
|
|
29
|
+
}
|
|
30
|
+
/** The runner an app makes once, in `src/server/layer.ts`. */
|
|
31
|
+
export interface Runner<ROut> {
|
|
32
|
+
/** Runs one write (or any non-GET) server function's program for the current request. */
|
|
33
|
+
readonly runApp: <A, E extends Tagged>(program: Effect.Effect<A, E, ROut | CallServices>) => Promise<Result<A, PlainTaggedError<E>>>;
|
|
34
|
+
/** Runs one GET read and sets its cache headers from `policy`. */
|
|
35
|
+
readonly runRead: <A, E extends Tagged>(policy: ReadCachePolicy<NoInfer<A>>, program: Effect.Effect<A, E, ROut | CallServices>) => Promise<Result<A, PlainTaggedError<E>>>;
|
|
36
|
+
/** Runs a program outside a server-function call (a cron, a page status probe): signed out, no edge cache. */
|
|
37
|
+
readonly runWithEnv: <A, E extends Tagged>(env: unknown, program: Effect.Effect<A, E, ROut | CallServices>) => Promise<Result<A, PlainTaggedError<E>>>;
|
|
38
|
+
/** The per-call services from explicit inputs (tests). */
|
|
39
|
+
readonly callServicesLayer: (inputs: CallInputs, record: CallRecord) => Layer.Layer<CallServices>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The app's runner: its module-level `layer` (services built once; they
|
|
43
|
+
* read `Bindings` when a method runs) plus the kit's per-call services,
|
|
44
|
+
* built from this request's `locals` (`env`, `ctx`, `session`; set by the
|
|
45
|
+
* Worker, or the dev middleware under `vite dev`). One `Context` per call,
|
|
46
|
+
* no Layer graph: building Layers per call cost ~1.2 ms of a 7 ms page on
|
|
47
|
+
* workerd (round 2).
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* export const AppLayer = Layer.mergeAll(PlanRepo.layer, AccountRepo.layer)
|
|
52
|
+
* export const { runApp, runRead, runWithEnv } = createRunner({ resources, layer: AppLayer })
|
|
53
|
+
*
|
|
54
|
+
* export async function saveDraft(raw: unknown) {
|
|
55
|
+
* 'use server'
|
|
56
|
+
* return runApp(saveDraftProgram(raw))
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare function createRunner<ROut>({ resources, layer, }: {
|
|
61
|
+
resources: ResourcesDecl;
|
|
62
|
+
layer: Layer.Layer<ROut>;
|
|
63
|
+
}): Runner<ROut>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Context, Layer } from 'effect';
|
|
2
|
+
import { Bindings, bindingsOf } from './bindings.js';
|
|
3
|
+
import { EdgeCache } from './edge-cache.js';
|
|
4
|
+
import { readCacheHeaders } from './read-cache.js';
|
|
5
|
+
import { RequestInfo } from './request-info.js';
|
|
6
|
+
import { requestHeader, requestLocals, requestUrl, withResponseHeaders, } from './request.js';
|
|
7
|
+
import { cookieHeaders, ResponseCookies } from './response-cookies.js';
|
|
8
|
+
import { runEffectResult } from './run-effect.js';
|
|
9
|
+
import { Session, sessionSlotFromLocals } from './session.js';
|
|
10
|
+
/**
|
|
11
|
+
* The app's runner: its module-level `layer` (services built once; they
|
|
12
|
+
* read `Bindings` when a method runs) plus the kit's per-call services,
|
|
13
|
+
* built from this request's `locals` (`env`, `ctx`, `session`; set by the
|
|
14
|
+
* Worker, or the dev middleware under `vite dev`). One `Context` per call,
|
|
15
|
+
* no Layer graph: building Layers per call cost ~1.2 ms of a 7 ms page on
|
|
16
|
+
* workerd (round 2).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* export const AppLayer = Layer.mergeAll(PlanRepo.layer, AccountRepo.layer)
|
|
21
|
+
* export const { runApp, runRead, runWithEnv } = createRunner({ resources, layer: AppLayer })
|
|
22
|
+
*
|
|
23
|
+
* export async function saveDraft(raw: unknown) {
|
|
24
|
+
* 'use server'
|
|
25
|
+
* return runApp(saveDraftProgram(raw))
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export function createRunner({ resources, layer, }) {
|
|
30
|
+
const bindings = bindingsOf(resources);
|
|
31
|
+
const callServicesLayer = (inputs, record) => Layer.succeedContext(Context.make(Bindings, bindings.lazy(inputs.env)).pipe(Context.add(Session, Session.forCall(sessionSlotFromLocals({ session: inputs.session }), () => {
|
|
32
|
+
record.sessionRead = true;
|
|
33
|
+
})), Context.add(EdgeCache, EdgeCache.forCall(inputs.ctx)), Context.add(ResponseCookies, ResponseCookies.forCall(inputs.requestUrl, record.cookies)), Context.add(RequestInfo, {
|
|
34
|
+
url: inputs.requestUrl,
|
|
35
|
+
client_ip: inputs.clientIp,
|
|
36
|
+
})));
|
|
37
|
+
const callLayer = (record) => {
|
|
38
|
+
const locals = requestLocals();
|
|
39
|
+
return callServicesLayer({
|
|
40
|
+
env: locals.env,
|
|
41
|
+
ctx: locals.ctx,
|
|
42
|
+
session: locals.session,
|
|
43
|
+
requestUrl: requestUrl(),
|
|
44
|
+
clientIp: requestHeader('CF-Connecting-IP'),
|
|
45
|
+
}, record);
|
|
46
|
+
};
|
|
47
|
+
const fresh = () => ({ sessionRead: false, cookies: [] });
|
|
48
|
+
return {
|
|
49
|
+
callServicesLayer,
|
|
50
|
+
runApp: async (program) => {
|
|
51
|
+
const record = fresh();
|
|
52
|
+
const result = await runEffectResult(program, layer, callLayer(record));
|
|
53
|
+
return withResponseHeaders(result, cookieHeaders(record.cookies));
|
|
54
|
+
},
|
|
55
|
+
runRead: async (policy, program) => {
|
|
56
|
+
const record = fresh();
|
|
57
|
+
const result = await runEffectResult(program, layer, callLayer(record));
|
|
58
|
+
const outcome = result;
|
|
59
|
+
return withResponseHeaders(result, [
|
|
60
|
+
...Object.entries(readCacheHeaders(policy, outcome, record)),
|
|
61
|
+
...cookieHeaders(record.cookies),
|
|
62
|
+
]);
|
|
63
|
+
},
|
|
64
|
+
runWithEnv: (env, program) => runEffectResult(program, layer, callServicesLayer({ env, requestUrl: new URL('http://localhost/') }, fresh())),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { Context, Effect, Layer } from 'effect';
|
|
2
|
+
import { Bindings } from './bindings.ts';
|
|
3
|
+
import { Unauthorized } from './errors.ts';
|
|
4
|
+
import { ResponseCookies } from './response-cookies.ts';
|
|
5
|
+
import type { D1Binding, D1Statement, ResourcesDecl } from '../logic/resources.ts';
|
|
6
|
+
/** How long a session lasts by default (server-side expiry; the cookie mirrors it). */
|
|
7
|
+
export declare const SESSION_TTL_SECONDS: number;
|
|
8
|
+
/** A signed-in session: the kit's row plus the app's user. Times are epoch ms. */
|
|
9
|
+
export interface SignedIn<U> {
|
|
10
|
+
readonly _tag: 'SignedIn';
|
|
11
|
+
/** SHA-256 (hex) of the cookie token: the `sessions` row id. */
|
|
12
|
+
readonly session_id: string;
|
|
13
|
+
readonly user_id: string;
|
|
14
|
+
readonly expires_at: number;
|
|
15
|
+
readonly user: U;
|
|
16
|
+
}
|
|
17
|
+
/** A session as `locals.session` holds it once resolved: plain data. */
|
|
18
|
+
export type SessionState<U = unknown> = {
|
|
19
|
+
readonly _tag: 'SignedOut';
|
|
20
|
+
} | SignedIn<U>;
|
|
21
|
+
export declare const SIGNED_OUT: {
|
|
22
|
+
readonly _tag: 'SignedOut';
|
|
23
|
+
};
|
|
24
|
+
/** A lookup not run yet: `resolve` reads D1 on its first call and memoizes the answer. */
|
|
25
|
+
export interface LazySession {
|
|
26
|
+
readonly _tag: 'Lazy';
|
|
27
|
+
readonly resolve: () => Promise<SessionState>;
|
|
28
|
+
}
|
|
29
|
+
/** What `locals.session` holds: a resolved session, or a lookup that runs when first needed. */
|
|
30
|
+
export type SessionSlot = SessionState | LazySession;
|
|
31
|
+
/** The cookie name and `Secure` flag for a request URL. */
|
|
32
|
+
export declare function sessionCookieSpec(url: URL): {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly secure: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** Bytes as base64url (no padding). */
|
|
37
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
38
|
+
/** A fresh opaque session token (256 bits). */
|
|
39
|
+
export declare function newSessionToken(): string;
|
|
40
|
+
/** The `sessions.session_id` for a token: SHA-256, hex. */
|
|
41
|
+
export declare function sessionIdOf(token: string): Promise<string>;
|
|
42
|
+
/** The session token in the request's cookie, if it has a well-formed one. */
|
|
43
|
+
export declare function sessionTokenOf(request: Request): string | undefined;
|
|
44
|
+
/** `Set-Cookie` for a new session. */
|
|
45
|
+
export declare function sessionCookie(url: URL, token: string, maxAge?: number): string;
|
|
46
|
+
/** `Set-Cookie` that removes the session cookie. */
|
|
47
|
+
export declare function clearSessionCookie(url: URL): string;
|
|
48
|
+
/** A resolved session for a slot (runs the lookup if it is lazy). */
|
|
49
|
+
export declare function resolveSlot(slot: SessionSlot): Promise<SessionState>;
|
|
50
|
+
/** `locals.session` as a slot (`SignedOut` when absent or malformed). */
|
|
51
|
+
export declare function sessionSlotFromLocals(locals: Readonly<Record<string, unknown>>): SessionSlot;
|
|
52
|
+
interface SessionShape {
|
|
53
|
+
/** This request's session (runs the lazy lookup on first use). Reading it marks the call as personal. */
|
|
54
|
+
readonly current: Effect.Effect<SessionState>;
|
|
55
|
+
}
|
|
56
|
+
declare const Session_base: Context.ServiceClass<Session, "@alecsibilia/ui-kit/server/Session", SessionShape>;
|
|
57
|
+
/**
|
|
58
|
+
* This request's session as an Effect service, provided per call from
|
|
59
|
+
* `locals.session` (like `Bindings`). `onRead` runs when a program reads
|
|
60
|
+
* it: `runRead` uses that to force `Cache-Control: private, no-store`.
|
|
61
|
+
* Apps read it through their `createSessions` helpers, which type the user.
|
|
62
|
+
*/
|
|
63
|
+
export declare class Session extends Session_base {
|
|
64
|
+
/** The service value for one call. */
|
|
65
|
+
static forCall(slot: SessionSlot, onRead?: () => void): SessionShape;
|
|
66
|
+
static layer(slot: SessionSlot, onRead?: () => void): Layer.Layer<Session>;
|
|
67
|
+
}
|
|
68
|
+
/** What an app hands the kit: how to find a session's user, and what to do when sessions end. */
|
|
69
|
+
export interface SessionsConfig<U> {
|
|
70
|
+
readonly resources: ResourcesDecl;
|
|
71
|
+
/** The user for a session's `user_id`, or `undefined` (the session then counts as signed out). */
|
|
72
|
+
readonly lookupUser: (args: {
|
|
73
|
+
readonly db: D1Binding;
|
|
74
|
+
readonly user_id: string;
|
|
75
|
+
}) => Promise<U | undefined>;
|
|
76
|
+
/** Runs after sessions end (sign-out, expiry cleanup) with their users' ids. */
|
|
77
|
+
readonly onEnded?: (args: {
|
|
78
|
+
readonly db: D1Binding;
|
|
79
|
+
readonly user_ids: readonly string[];
|
|
80
|
+
}) => Promise<void>;
|
|
81
|
+
readonly ttlSeconds?: number;
|
|
82
|
+
}
|
|
83
|
+
/** The app's sessions: typed reads, sign-in and sign-out, and the expiry cleanup. */
|
|
84
|
+
export interface Sessions<U> {
|
|
85
|
+
readonly config: SessionsConfig<U>;
|
|
86
|
+
/** The D1 binding name that holds the `sessions` table. */
|
|
87
|
+
readonly database: string;
|
|
88
|
+
/** The session for a request, run once (one or two indexed D1 reads; none without a cookie). */
|
|
89
|
+
readonly resolve: (request: Request, db: D1Binding, nowMs: number) => Promise<SessionState<U>>;
|
|
90
|
+
/** The request's session as a lazy lookup (`locals.session`). `db` is called only when it runs. */
|
|
91
|
+
readonly lazy: (request: Request, db: () => D1Binding, nowMs: number) => SessionSlot;
|
|
92
|
+
/** This call's session, typed. Reading it marks the call as personal. */
|
|
93
|
+
readonly current: Effect.Effect<SessionState<U>, never, Session>;
|
|
94
|
+
/** The signed-in session, or a typed `Unauthorized`. */
|
|
95
|
+
readonly require: Effect.Effect<SignedIn<U>, Unauthorized, Session>;
|
|
96
|
+
/**
|
|
97
|
+
* Starts a session for `user_id`: inserts the row (after `before`, in one
|
|
98
|
+
* D1 transaction, so an app creates its user and the session together)
|
|
99
|
+
* and sets the cookie. Returns when the session ends (epoch ms).
|
|
100
|
+
*/
|
|
101
|
+
readonly signIn: (args: {
|
|
102
|
+
readonly user_id: string;
|
|
103
|
+
readonly before?: readonly D1Statement[];
|
|
104
|
+
}) => Effect.Effect<{
|
|
105
|
+
readonly expires_at: number;
|
|
106
|
+
}, never, Bindings | ResponseCookies>;
|
|
107
|
+
/** Ends this call's session (if any) and clears the cookie. */
|
|
108
|
+
readonly signOut: Effect.Effect<void, never, Bindings | ResponseCookies | Session>;
|
|
109
|
+
/** Deletes up to `limit` expired sessions (oldest first); returns how many. */
|
|
110
|
+
readonly purgeExpired: (limit: number) => Effect.Effect<number, never, Bindings>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The app's sessions over the kit's `sessions` table.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* export const sessions = createSessions<DemoUser>({
|
|
118
|
+
* resources,
|
|
119
|
+
* lookupUser: ({ db, user_id }) => findUser(db, user_id),
|
|
120
|
+
* })
|
|
121
|
+
* const session = yield* sessions.require
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare function createSessions<U>(config: SessionsConfig<U>): Sessions<U>;
|
|
125
|
+
export {};
|