@vvedantb/server 0.4.1 → 0.6.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 +34 -0
- package/README.md +12 -5
- package/dist/artifacts/debounce.d.ts +16 -0
- package/dist/artifacts/debounce.js +49 -0
- package/dist/artifacts/document.d.ts +26 -0
- package/dist/artifacts/document.js +61 -0
- package/dist/artifacts/index.d.ts +8 -0
- package/dist/artifacts/index.js +8 -0
- package/dist/artifacts/limits.d.ts +21 -0
- package/dist/artifacts/limits.js +23 -0
- package/dist/artifacts/protocol.d.ts +45 -0
- package/dist/artifacts/protocol.js +243 -0
- package/dist/artifacts/schemas.d.ts +80 -0
- package/dist/artifacts/schemas.js +103 -0
- package/dist/artifacts/stateOps.d.ts +39 -0
- package/dist/artifacts/stateOps.js +92 -0
- package/dist/artifacts/storageShim.d.ts +9 -0
- package/dist/artifacts/storageShim.js +32 -0
- package/dist/artifacts/templates.d.ts +33 -0
- package/dist/artifacts/templates.js +496 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.js +2 -0
- package/dist/sandbox/runtime.d.ts +80 -0
- package/dist/sandbox/runtime.js +289 -0
- package/dist/sandbox/serialize.d.ts +10 -0
- package/dist/sandbox/serialize.js +21 -0
- package/docs/artifacts.md +116 -0
- package/docs/sandbox.md +140 -0
- package/package.json +18 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
Additive: a pure artifacts core joins the root. Nothing in 0.5.0 changes. See `docs/artifacts.md`.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `createArtifactSchemas(z)` (zod 3.25+ or 4, passed in): `artifactType`, `artifactFormat`, `stateSpec`, `quizBodyV1`, `flashcardsBodyV1`, `listRow`, `detailRow`, and `validateArtifactBody(type, format, body, schemaVersion?)`, which caps bodies at 400,000 characters and allows `json` only for quiz and flashcards v1. Constants `ARTIFACT_TYPES`, `ARTIFACT_FORMATS`, `ARTIFACT_JSON_TYPES`, `ARTIFACT_TITLE_MAX_CHARS`, `ARTIFACT_DESCRIPTION_MAX_CHARS`, `ARTIFACT_BODY_MAX_CHARS`. Types `ArtifactType`, `ArtifactFormat`, `ArtifactStateSpec`, `QuizBodyV1`, `FlashcardsBodyV1`, `ArtifactOrigin`, `ArtifactListRow`, `ArtifactDetailRow`, `ArtifactSchemas`, `ArtifactBodyValidation`.
|
|
10
|
+
- State: limits (32 keys, 64-character keys, 16 KiB per value, 64 KiB in total, 1 s between writes, 400/4,000 daily writes, 5 s/30 s save debounce, 10 versions kept), `applyArtifactStateOp`, `applyArtifactStatePatch`, `validateArtifactStateMap`, `parseArtifactStateOp`, `utcDayKey`, `utf8ByteLength`, `createTrailingMaxDebounce`, and the storage-shim prefixes and helpers (`ls:`, `ss:`).
|
|
11
|
+
- Rendering: `buildQuizHtml`, `buildFlashcardsHtml`, `htmlFromArtifactTemplate` with lenient `parseQuizTemplate` and `parseFlashcardsTemplate`, `wrapArtifactDocument(body, format, snapshot?, { title?, template?, stateGlobalAliases? })`, `wrapArtifactHtml`, `artifactGuestScript`, `GUEST_BOOTSTRAP_SCRIPT`, `ARTIFACT_CSP`, `formatFromLanguage`, `ARTIFACT_FORMAT_FILES` and `artifactFileName`.
|
|
12
|
+
- Bridge messages with neutral names: `artifact:ready`, `artifact:port`, `artifact:state`, `artifact:state-result`. The guest exposes `window.artifactState`, plus `window[alias].state` for each alias the host passes (`assertStateGlobalAliases` refuses non-identifiers and globals such as `document`). The built-in pages use `window.artifactState`.
|
|
13
|
+
- Tests: `tests/artifacts` (protocol and alias injection, the guest run in a VM realm, state limit edges, debounce, templates, document formats, schema v1 round trips under zod 4 and 3.25, and a check that no app name appears in the source or shipped docs). `tests-node` imports the new exports from the built package with no peer installed, type-checks them for zod 4 and 3.25 consumers, and bundles them for Convex V8.
|
|
14
|
+
|
|
15
|
+
### Changed (from the app code this came from)
|
|
16
|
+
|
|
17
|
+
- The snapshot global is `__ARTIFACT_SNAPSHOT__`. The guest limit checks use the exported constants.
|
|
18
|
+
- `applyArtifactStatePatch` returns the current data unchanged when any set or remove fails. Before, a failing set returned the partly applied data.
|
|
19
|
+
- The quiz and flashcards builders are `buildQuizHtml` and `buildFlashcardsHtml`; their card and question types are `Flashcard` and `QuizQuestion`.
|
|
20
|
+
|
|
21
|
+
## 0.5.0
|
|
22
|
+
|
|
23
|
+
Additive: a QuickJS code sandbox joins the root. Nothing in 0.4.1 changes.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- `runSandboxedScript(code, tools, limits?, options?)`: runs untrusted JavaScript (the body of an async function) in a fresh QuickJS runtime. The script calls host tools with `await tools.<name>(args)`, logs with `console`, and returns a JSON value. Never throws; resolves to `{ ok, result | error, logs, calls, ms }`. See `docs/sandbox.md`.
|
|
28
|
+
- `DEFAULT_EXECUTE_LIMITS`: 60 s wall clock, 64 MB heap, 1 MB stack, 50 tool calls of which at most 10 mutating, logs capped at 200 lines of 2,000 characters. Every field can be overridden per run.
|
|
29
|
+
- `options.globals`: JSON-serialisable values set as VM globals, for example `{ args }`. Names that would replace an existing global are refused.
|
|
30
|
+
- `options.onCall`: called before each tool call with `{ name, args, mutating }`. Returns `{ allow: true }`, `{ allow: false, error }` (the script's call rejects; the tool does not run) or `{ stub }` (the call resolves to the stub; the tool does not run and the call is recorded with `skipped: true`). Refused and stubbed calls count against the call caps.
|
|
31
|
+
- `serializeExecuteOutcome(outcome, maxChars?)` and `DEFAULT_RESULT_CHAR_CAP` (100,000): pretty JSON of an outcome for a tool reply; a larger successful result becomes `{ truncated, note, resultPreview }`.
|
|
32
|
+
- Types: `SandboxTool`, `ExecuteLimits`, `ExecuteOutcome`, `SandboxOptions`, `SandboxCall`, `SandboxCallDecision`, `SandboxCallRecord`.
|
|
33
|
+
- New optional peers: `quickjs-emscripten-core` and `@jitl/quickjs-singlefile-cjs-release-sync` `^0.32.0`. They load on the first `runSandboxedScript` call, never when the root is imported. Without them the call returns `ok: false` with `Sandbox unavailable: …`.
|
|
34
|
+
- `package.json` `browser` field: maps both QuickJS packages to empty modules, so browser-platform bundles of the root (Convex V8) never include QuickJS or its Node built-ins, even when it is installed.
|
|
35
|
+
- Tests: `tests/sandbox` runs against real QuickJS (limits, deadline, out of memory, stack overflow, stalled promise, error mapping, disposal after a timeout, log caps, result preview, globals, `onCall` refusal and stubs, call caps). `tests-node/bundle.mjs` bundles the root for Convex V8 with QuickJS installed and checks no output contains it, and runs a Node bundle of the sandbox with no `node_modules`. `tests-node/esm-exports.mjs` covers the new exports and types, and the sandbox with and without QuickJS installed.
|
|
36
|
+
|
|
3
37
|
## 0.4.1
|
|
4
38
|
|
|
5
39
|
Docs and comments only; no runtime change.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends, Convex optimistic updates
|
|
3
|
+
Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm install @vvedantb/server
|
|
@@ -19,6 +19,8 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
|
|
|
19
19
|
| Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
|
|
20
20
|
| Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
|
|
21
21
|
| MCP OAuth client | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. | [docs/mcp-oauth-client.md](docs/mcp-oauth-client.md) |
|
|
22
|
+
| Artifacts core | Pure, no DOM: Zod contract for artifact rows and typed bodies (`createArtifactSchemas`, `validateArtifactBody`), state limits and ops, the host's save debounce, built-in quiz and flashcards pages, and `wrapArtifactDocument` (CSP plus a guest state bridge with host-given global aliases). | [docs/artifacts.md](docs/artifacts.md) |
|
|
23
|
+
| Code sandbox | Node only: `runSandboxedScript` runs untrusted JavaScript in QuickJS (WASM) with a `tools` proxy to host handlers, time, heap, stack, call and log limits, injected `globals`, and an `onCall` hook for allow-lists and dry runs. QuickJS loads on first call. | [docs/sandbox.md](docs/sandbox.md) |
|
|
22
24
|
|
|
23
25
|
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
24
26
|
|
|
@@ -27,27 +29,32 @@ Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
|
27
29
|
All are optional. None is imported when the root loads.
|
|
28
30
|
|
|
29
31
|
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
30
|
-
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema`.
|
|
32
|
+
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema` or `createArtifactSchemas`.
|
|
31
33
|
- `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
|
|
32
34
|
- `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
|
|
35
|
+
- `quickjs-emscripten-core` and `@jitl/quickjs-singlefile-cjs-release-sync` `^0.32.0`: only for `runSandboxedScript`, which imports them on first call. The `browser` field maps both to empty modules, so browser-platform bundles (Convex V8) of the root never include them.
|
|
33
36
|
|
|
34
37
|
No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types in `dist`, built on pack.
|
|
35
38
|
|
|
36
39
|
## Layout
|
|
37
40
|
|
|
38
41
|
```
|
|
39
|
-
src/index.ts the only export: re-exports the
|
|
42
|
+
src/index.ts the only export: re-exports the six folders
|
|
40
43
|
src/convex/ Convex helpers and optimistic updates
|
|
41
44
|
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
42
45
|
src/mcp-oauth-client/ MCP OAuth client helpers (Node only; lazy node:http and SDK imports)
|
|
43
46
|
src/crypto/ WebCrypto primitives
|
|
47
|
+
src/sandbox/ QuickJS code sandbox (Node only; lazy QuickJS import)
|
|
48
|
+
src/artifacts/ artifacts core (pure strings and data; runs anywhere)
|
|
44
49
|
tests/convex/ vitest
|
|
45
50
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
46
51
|
tests/mcp-oauth-client/ vitest, against fake MCP and authorization servers
|
|
47
52
|
tests/crypto/ vitest, with published vectors and app format parity
|
|
53
|
+
tests/sandbox/ vitest, against real QuickJS
|
|
54
|
+
tests/artifacts/ vitest, including the guest bootstrap in a VM realm and a no-app-name check
|
|
48
55
|
tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
|
|
49
|
-
Convex V8 and Electron
|
|
50
|
-
docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, migration.md, migrated/<app>/
|
|
56
|
+
Convex V8 and Node/Electron bundles with esbuild (bundle.mjs)
|
|
57
|
+
docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
|
|
51
58
|
scripts/ capture-sdk-fixtures.mjs
|
|
52
59
|
```
|
|
53
60
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type DebounceTimers = {
|
|
2
|
+
setTimeout: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
|
|
3
|
+
clearTimeout: (id: ReturnType<typeof setTimeout>) => void;
|
|
4
|
+
};
|
|
5
|
+
export type TrailingMaxDebounce = {
|
|
6
|
+
schedule(): void;
|
|
7
|
+
flushNow(): void;
|
|
8
|
+
cancel(): void;
|
|
9
|
+
readonly isPending: boolean;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Calls `flush` `trailingMs` after the last `schedule()`, and at the latest
|
|
13
|
+
* `maxMs` after the first one, so steady changes still save. `flushNow()`
|
|
14
|
+
* runs a pending flush at once (for `pagehide`); `cancel()` drops it.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createTrailingMaxDebounce(flush: () => void, trailingMs?: number, maxMs?: number, timers?: DebounceTimers): TrailingMaxDebounce;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_WAIT_MS } from "./limits.js";
|
|
2
|
+
/**
|
|
3
|
+
* Calls `flush` `trailingMs` after the last `schedule()`, and at the latest
|
|
4
|
+
* `maxMs` after the first one, so steady changes still save. `flushNow()`
|
|
5
|
+
* runs a pending flush at once (for `pagehide`); `cancel()` drops it.
|
|
6
|
+
*/
|
|
7
|
+
export function createTrailingMaxDebounce(flush, trailingMs = ARTIFACT_STATE_DEBOUNCE_MS, maxMs = ARTIFACT_STATE_MAX_WAIT_MS, timers = {
|
|
8
|
+
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
9
|
+
clearTimeout: (id) => globalThis.clearTimeout(id),
|
|
10
|
+
}) {
|
|
11
|
+
let trailingId;
|
|
12
|
+
let maxId;
|
|
13
|
+
let pending = false;
|
|
14
|
+
function clearTimers() {
|
|
15
|
+
if (trailingId !== undefined)
|
|
16
|
+
timers.clearTimeout(trailingId);
|
|
17
|
+
if (maxId !== undefined)
|
|
18
|
+
timers.clearTimeout(maxId);
|
|
19
|
+
trailingId = undefined;
|
|
20
|
+
maxId = undefined;
|
|
21
|
+
}
|
|
22
|
+
function run() {
|
|
23
|
+
clearTimers();
|
|
24
|
+
if (!pending)
|
|
25
|
+
return;
|
|
26
|
+
pending = false;
|
|
27
|
+
flush();
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
schedule() {
|
|
31
|
+
pending = true;
|
|
32
|
+
if (trailingId !== undefined)
|
|
33
|
+
timers.clearTimeout(trailingId);
|
|
34
|
+
trailingId = timers.setTimeout(run, trailingMs);
|
|
35
|
+
if (maxId === undefined)
|
|
36
|
+
maxId = timers.setTimeout(run, maxMs);
|
|
37
|
+
},
|
|
38
|
+
flushNow() {
|
|
39
|
+
run();
|
|
40
|
+
},
|
|
41
|
+
cancel() {
|
|
42
|
+
pending = false;
|
|
43
|
+
clearTimers();
|
|
44
|
+
},
|
|
45
|
+
get isPending() {
|
|
46
|
+
return pending;
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type ArtifactGuestOptions } from "./protocol.js";
|
|
2
|
+
import type { ArtifactFormat } from "./schemas.js";
|
|
3
|
+
import type { ArtifactStateMap } from "./stateOps.js";
|
|
4
|
+
import { type ArtifactTemplateName } from "./templates.js";
|
|
5
|
+
export type WrapArtifactDocumentOptions = ArtifactGuestOptions & {
|
|
6
|
+
/** Heading for a built-in template when the body has no title. Default "Artifact". */
|
|
7
|
+
title?: string;
|
|
8
|
+
/** From `stateSpec.template`. Tried first for any format; `json` bodies without one try both templates. */
|
|
9
|
+
template?: ArtifactTemplateName;
|
|
10
|
+
};
|
|
11
|
+
/** The body format for a fenced code block's language: html, svg and markdown render; anything else is code. */
|
|
12
|
+
export declare function formatFromLanguage(language: string | undefined): "html" | "markdown" | "svg" | "code";
|
|
13
|
+
/**
|
|
14
|
+
* The `srcdoc` for an artifact: the body as a document (a built-in template
|
|
15
|
+
* for quiz and flashcards JSON), with the CSP and the guest state bootstrap
|
|
16
|
+
* (snapshot plus `stateGlobalAliases`) at the start of <head>. Render it in an
|
|
17
|
+
* iframe with `sandbox="allow-scripts"` and no `allow-same-origin`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function wrapArtifactDocument(body: string, format: ArtifactFormat, snapshot?: ArtifactStateMap, options?: WrapArtifactDocumentOptions): string;
|
|
20
|
+
/** File extension and MIME type for downloading a body of each format. */
|
|
21
|
+
export declare const ARTIFACT_FORMAT_FILES: Record<ArtifactFormat, {
|
|
22
|
+
extension: string;
|
|
23
|
+
mime: string;
|
|
24
|
+
}>;
|
|
25
|
+
/** A download file name: the title with characters that file systems refuse replaced by "-", plus the format's extension. */
|
|
26
|
+
export declare function artifactFileName(title: string, format: ArtifactFormat): string;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { wrapArtifactHtml } from "./protocol.js";
|
|
2
|
+
import { htmlFromArtifactTemplate } from "./templates.js";
|
|
3
|
+
/** The body format for a fenced code block's language: html, svg and markdown render; anything else is code. */
|
|
4
|
+
export function formatFromLanguage(language) {
|
|
5
|
+
const normalized = (language ?? "html").toLowerCase();
|
|
6
|
+
if (normalized === "html" || normalized === "htm")
|
|
7
|
+
return "html";
|
|
8
|
+
if (normalized === "svg")
|
|
9
|
+
return "svg";
|
|
10
|
+
if (normalized === "md" || normalized === "markdown")
|
|
11
|
+
return "markdown";
|
|
12
|
+
return "code";
|
|
13
|
+
}
|
|
14
|
+
function escapeText(value) {
|
|
15
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
16
|
+
}
|
|
17
|
+
function plainTextDocument(body) {
|
|
18
|
+
return `<!doctype html><html><head><meta charset="utf-8"/><style>body{font-family:system-ui,sans-serif;margin:16px;white-space:pre-wrap}</style></head><body><pre>${escapeText(body)}</pre></body></html>`;
|
|
19
|
+
}
|
|
20
|
+
/** A full HTML document for `body` before the guest is injected. Markdown and code show as escaped text. */
|
|
21
|
+
function previewDocument(body, format, options) {
|
|
22
|
+
if (options.template !== undefined || format === "json") {
|
|
23
|
+
const templated = htmlFromArtifactTemplate({
|
|
24
|
+
title: options.title ?? "Artifact",
|
|
25
|
+
content: body,
|
|
26
|
+
template: options.template,
|
|
27
|
+
});
|
|
28
|
+
if (templated)
|
|
29
|
+
return templated;
|
|
30
|
+
}
|
|
31
|
+
if (format === "svg") {
|
|
32
|
+
return `<!doctype html><html><body style="margin:0;display:grid;place-items:center;min-height:100vh;background:#fff">${body}</body></html>`;
|
|
33
|
+
}
|
|
34
|
+
if (format === "html") {
|
|
35
|
+
return body.includes("<html")
|
|
36
|
+
? body
|
|
37
|
+
: `<!doctype html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><style>body{font-family:system-ui,sans-serif;margin:16px}</style></head><body>${body}</body></html>`;
|
|
38
|
+
}
|
|
39
|
+
return plainTextDocument(body);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The `srcdoc` for an artifact: the body as a document (a built-in template
|
|
43
|
+
* for quiz and flashcards JSON), with the CSP and the guest state bootstrap
|
|
44
|
+
* (snapshot plus `stateGlobalAliases`) at the start of <head>. Render it in an
|
|
45
|
+
* iframe with `sandbox="allow-scripts"` and no `allow-same-origin`.
|
|
46
|
+
*/
|
|
47
|
+
export function wrapArtifactDocument(body, format, snapshot, options = {}) {
|
|
48
|
+
return wrapArtifactHtml(previewDocument(body, format, options), snapshot, options);
|
|
49
|
+
}
|
|
50
|
+
/** File extension and MIME type for downloading a body of each format. */
|
|
51
|
+
export const ARTIFACT_FORMAT_FILES = {
|
|
52
|
+
html: { extension: "html", mime: "text/html" },
|
|
53
|
+
markdown: { extension: "md", mime: "text/markdown" },
|
|
54
|
+
svg: { extension: "svg", mime: "image/svg+xml" },
|
|
55
|
+
code: { extension: "txt", mime: "text/plain" },
|
|
56
|
+
json: { extension: "json", mime: "application/json" },
|
|
57
|
+
};
|
|
58
|
+
/** A download file name: the title with characters that file systems refuse replaced by "-", plus the format's extension. */
|
|
59
|
+
export function artifactFileName(title, format) {
|
|
60
|
+
return `${title.replace(/[/\\?%*:|"<>]/g, "-")}.${ARTIFACT_FORMAT_FILES[format].extension}`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createTrailingMaxDebounce, type DebounceTimers, type TrailingMaxDebounce } from "./debounce.js";
|
|
2
|
+
export { ARTIFACT_FORMAT_FILES, artifactFileName, formatFromLanguage, wrapArtifactDocument, type WrapArtifactDocumentOptions, } from "./document.js";
|
|
3
|
+
export { ARTIFACT_BODY_MAX_CHARS, ARTIFACT_STATE_DAILY_WRITES, ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, ARTIFACT_STATE_MAX_WAIT_MS, ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS, ARTIFACT_VERSION_KEEP, utcDayKey, utf8ByteLength, } from "./limits.js";
|
|
4
|
+
export { ARTIFACT_ALIASES_GLOBAL, ARTIFACT_CSP, ARTIFACT_PORT_TYPE, ARTIFACT_READY_TYPE, ARTIFACT_SNAPSHOT_GLOBAL, ARTIFACT_STATE_RESULT_TYPE, ARTIFACT_STATE_TYPE, GUEST_BOOTSTRAP_SCRIPT, artifactGuestScript, assertStateGlobalAliases, wrapArtifactHtml, type ArtifactGuestOptions, } from "./protocol.js";
|
|
5
|
+
export { ARTIFACT_DESCRIPTION_MAX_CHARS, ARTIFACT_FORMATS, ARTIFACT_JSON_TYPES, ARTIFACT_TITLE_MAX_CHARS, ARTIFACT_TYPES, createArtifactSchemas, type ArtifactBodyValidation, type ArtifactDetailRow, type ArtifactFormat, type ArtifactListRow, type ArtifactOrigin, type ArtifactSchemas, type ArtifactStateSpec, type ArtifactType, type FlashcardsBodyV1, type QuizBodyV1, } from "./schemas.js";
|
|
6
|
+
export { applyArtifactStateOp, applyArtifactStatePatch, parseArtifactStateOp, validateArtifactStateMap, type ArtifactStateMap, type ArtifactStateOp, type ArtifactStateOpResult, type ArtifactStatePatch, } from "./stateOps.js";
|
|
7
|
+
export { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX, clearPrefixedKeys, prefixedStorageKey, storageView, unprefixStorageKey, } from "./storageShim.js";
|
|
8
|
+
export { buildFlashcardsHtml, buildQuizHtml, htmlFromArtifactTemplate, parseFlashcardsTemplate, parseQuizTemplate, type ArtifactTemplateName, type Flashcard, type QuizQuestion, } from "./templates.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createTrailingMaxDebounce } from "./debounce.js";
|
|
2
|
+
export { ARTIFACT_FORMAT_FILES, artifactFileName, formatFromLanguage, wrapArtifactDocument, } from "./document.js";
|
|
3
|
+
export { ARTIFACT_BODY_MAX_CHARS, ARTIFACT_STATE_DAILY_WRITES, ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, ARTIFACT_STATE_MAX_WAIT_MS, ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS, ARTIFACT_VERSION_KEEP, utcDayKey, utf8ByteLength, } from "./limits.js";
|
|
4
|
+
export { ARTIFACT_ALIASES_GLOBAL, ARTIFACT_CSP, ARTIFACT_PORT_TYPE, ARTIFACT_READY_TYPE, ARTIFACT_SNAPSHOT_GLOBAL, ARTIFACT_STATE_RESULT_TYPE, ARTIFACT_STATE_TYPE, GUEST_BOOTSTRAP_SCRIPT, artifactGuestScript, assertStateGlobalAliases, wrapArtifactHtml, } from "./protocol.js";
|
|
5
|
+
export { ARTIFACT_DESCRIPTION_MAX_CHARS, ARTIFACT_FORMATS, ARTIFACT_JSON_TYPES, ARTIFACT_TITLE_MAX_CHARS, ARTIFACT_TYPES, createArtifactSchemas, } from "./schemas.js";
|
|
6
|
+
export { applyArtifactStateOp, applyArtifactStatePatch, parseArtifactStateOp, validateArtifactStateMap, } from "./stateOps.js";
|
|
7
|
+
export { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX, clearPrefixedKeys, prefixedStorageKey, storageView, unprefixStorageKey, } from "./storageShim.js";
|
|
8
|
+
export { buildFlashcardsHtml, buildQuizHtml, htmlFromArtifactTemplate, parseFlashcardsTemplate, parseQuizTemplate, } from "./templates.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Largest artifact body, in characters. Convex documents stop at 1 MiB. */
|
|
2
|
+
export declare const ARTIFACT_BODY_MAX_CHARS = 400000;
|
|
3
|
+
/** Versions kept per artifact; older ones are pruned. */
|
|
4
|
+
export declare const ARTIFACT_VERSION_KEEP = 10;
|
|
5
|
+
export declare const ARTIFACT_STATE_MAX_KEYS = 32;
|
|
6
|
+
export declare const ARTIFACT_STATE_MAX_VALUE_BYTES: number;
|
|
7
|
+
export declare const ARTIFACT_STATE_MAX_TOTAL_BYTES: number;
|
|
8
|
+
export declare const ARTIFACT_STATE_MAX_KEY_LENGTH = 64;
|
|
9
|
+
/** Server side: a second state write for the same artifact and user within this window is refused. */
|
|
10
|
+
export declare const ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS = 1000;
|
|
11
|
+
/** Host side: state is saved this long after the last change, and at least this often while changes keep coming. */
|
|
12
|
+
export declare const ARTIFACT_STATE_DEBOUNCE_MS = 5000;
|
|
13
|
+
export declare const ARTIFACT_STATE_MAX_WAIT_MS = 30000;
|
|
14
|
+
/** State writes per user per UTC day (see `utcDayKey`). */
|
|
15
|
+
export declare const ARTIFACT_STATE_DAILY_WRITES: {
|
|
16
|
+
readonly free: 400;
|
|
17
|
+
readonly pro: 4000;
|
|
18
|
+
};
|
|
19
|
+
export declare function utf8ByteLength(value: string): number;
|
|
20
|
+
/** The UTC day of `now` as a number, for example 20261022. */
|
|
21
|
+
export declare function utcDayKey(now: number): number;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Largest artifact body, in characters. Convex documents stop at 1 MiB. */
|
|
2
|
+
export const ARTIFACT_BODY_MAX_CHARS = 400_000;
|
|
3
|
+
/** Versions kept per artifact; older ones are pruned. */
|
|
4
|
+
export const ARTIFACT_VERSION_KEEP = 10;
|
|
5
|
+
export const ARTIFACT_STATE_MAX_KEYS = 32;
|
|
6
|
+
export const ARTIFACT_STATE_MAX_VALUE_BYTES = 16 * 1024;
|
|
7
|
+
export const ARTIFACT_STATE_MAX_TOTAL_BYTES = 64 * 1024;
|
|
8
|
+
export const ARTIFACT_STATE_MAX_KEY_LENGTH = 64;
|
|
9
|
+
/** Server side: a second state write for the same artifact and user within this window is refused. */
|
|
10
|
+
export const ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS = 1000;
|
|
11
|
+
/** Host side: state is saved this long after the last change, and at least this often while changes keep coming. */
|
|
12
|
+
export const ARTIFACT_STATE_DEBOUNCE_MS = 5000;
|
|
13
|
+
export const ARTIFACT_STATE_MAX_WAIT_MS = 30_000;
|
|
14
|
+
/** State writes per user per UTC day (see `utcDayKey`). */
|
|
15
|
+
export const ARTIFACT_STATE_DAILY_WRITES = { free: 400, pro: 4000 };
|
|
16
|
+
export function utf8ByteLength(value) {
|
|
17
|
+
return new TextEncoder().encode(value).byteLength;
|
|
18
|
+
}
|
|
19
|
+
/** The UTC day of `now` as a number, for example 20261022. */
|
|
20
|
+
export function utcDayKey(now) {
|
|
21
|
+
const date = new Date(now);
|
|
22
|
+
return date.getUTCFullYear() * 10000 + (date.getUTCMonth() + 1) * 100 + date.getUTCDate();
|
|
23
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ArtifactStateMap } from "./stateOps.js";
|
|
2
|
+
/** No network, no frames, no forms: the artifact runs offline in a sandboxed iframe or WebView. */
|
|
3
|
+
export declare const ARTIFACT_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
|
4
|
+
/** Guest → host (window message): the bootstrap ran; send the port. */
|
|
5
|
+
export declare const ARTIFACT_READY_TYPE = "artifact:ready";
|
|
6
|
+
/** Host → guest (window message, with a MessagePort): state requests go over this port from now on. */
|
|
7
|
+
export declare const ARTIFACT_PORT_TYPE = "artifact:port";
|
|
8
|
+
/** Guest → host: `{ type, requestId, op, key?, value? }`. Parse with `parseArtifactStateOp`. */
|
|
9
|
+
export declare const ARTIFACT_STATE_TYPE = "artifact:state";
|
|
10
|
+
/** Host → guest: `{ type, requestId, ok, value?, error? }`. */
|
|
11
|
+
export declare const ARTIFACT_STATE_RESULT_TYPE = "artifact:state-result";
|
|
12
|
+
/** The global the host sets before the bootstrap runs: the state snapshot. The bootstrap deletes it. */
|
|
13
|
+
export declare const ARTIFACT_SNAPSHOT_GLOBAL = "__ARTIFACT_SNAPSHOT__";
|
|
14
|
+
/** The global the host sets before the bootstrap runs: extra names for the state API. The bootstrap deletes it. */
|
|
15
|
+
export declare const ARTIFACT_ALIASES_GLOBAL = "__ARTIFACT_ALIASES__";
|
|
16
|
+
/**
|
|
17
|
+
* Runs first in the guest document. Exposes `window.artifactState`
|
|
18
|
+
* (`get`, `set`, `getAll`, `remove`, `reset`; promises; values are JSON), and
|
|
19
|
+
* `window[alias].state` for each alias in `window.__ARTIFACT_ALIASES__`.
|
|
20
|
+
* Replaces `localStorage` and `sessionStorage` with shims over the same state
|
|
21
|
+
* (keys prefixed `ls:` and `ss:`). Writes over the state limits fail in the
|
|
22
|
+
* guest before they reach the host. Talks to the host over a MessagePort, or
|
|
23
|
+
* `window.ReactNativeWebView.postMessage` in a React Native WebView.
|
|
24
|
+
*/
|
|
25
|
+
export declare const GUEST_BOOTSTRAP_SCRIPT: string;
|
|
26
|
+
export type ArtifactGuestOptions = {
|
|
27
|
+
/**
|
|
28
|
+
* Extra globals for the state API: `["app"]` makes `window.app.state` the
|
|
29
|
+
* same object as `window.artifactState`. Each must be a JavaScript
|
|
30
|
+
* identifier and must not name a built-in global (`window`, `document`, …).
|
|
31
|
+
*/
|
|
32
|
+
stateGlobalAliases?: readonly string[];
|
|
33
|
+
};
|
|
34
|
+
/** Throws on an alias that is not an identifier or would replace a global the page or the bootstrap needs. */
|
|
35
|
+
export declare function assertStateGlobalAliases(aliases: readonly string[]): void;
|
|
36
|
+
/** JSON for an inline <script>: `<` is escaped so the data cannot close the script element. */
|
|
37
|
+
export declare function embedJsonInScript(value: object): string;
|
|
38
|
+
/**
|
|
39
|
+
* The inline script for the guest: the snapshot and aliases, then
|
|
40
|
+
* `GUEST_BOOTSTRAP_SCRIPT`. A React Native WebView can pass it as
|
|
41
|
+
* `injectedJavaScriptBeforeContentLoaded`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function artifactGuestScript(snapshot?: ArtifactStateMap, options?: ArtifactGuestOptions): string;
|
|
44
|
+
/** Put the CSP meta tag and the guest script at the start of the document's <head>, adding a <head> or a whole document when missing. */
|
|
45
|
+
export declare function wrapArtifactHtml(html: string, snapshot?: ArtifactStateMap, options?: ArtifactGuestOptions): string;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, } from "./limits.js";
|
|
2
|
+
import { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX } from "./storageShim.js";
|
|
3
|
+
/** No network, no frames, no forms: the artifact runs offline in a sandboxed iframe or WebView. */
|
|
4
|
+
export const ARTIFACT_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
|
5
|
+
/** Guest → host (window message): the bootstrap ran; send the port. */
|
|
6
|
+
export const ARTIFACT_READY_TYPE = "artifact:ready";
|
|
7
|
+
/** Host → guest (window message, with a MessagePort): state requests go over this port from now on. */
|
|
8
|
+
export const ARTIFACT_PORT_TYPE = "artifact:port";
|
|
9
|
+
/** Guest → host: `{ type, requestId, op, key?, value? }`. Parse with `parseArtifactStateOp`. */
|
|
10
|
+
export const ARTIFACT_STATE_TYPE = "artifact:state";
|
|
11
|
+
/** Host → guest: `{ type, requestId, ok, value?, error? }`. */
|
|
12
|
+
export const ARTIFACT_STATE_RESULT_TYPE = "artifact:state-result";
|
|
13
|
+
/** The global the host sets before the bootstrap runs: the state snapshot. The bootstrap deletes it. */
|
|
14
|
+
export const ARTIFACT_SNAPSHOT_GLOBAL = "__ARTIFACT_SNAPSHOT__";
|
|
15
|
+
/** The global the host sets before the bootstrap runs: extra names for the state API. The bootstrap deletes it. */
|
|
16
|
+
export const ARTIFACT_ALIASES_GLOBAL = "__ARTIFACT_ALIASES__";
|
|
17
|
+
/**
|
|
18
|
+
* Runs first in the guest document. Exposes `window.artifactState`
|
|
19
|
+
* (`get`, `set`, `getAll`, `remove`, `reset`; promises; values are JSON), and
|
|
20
|
+
* `window[alias].state` for each alias in `window.__ARTIFACT_ALIASES__`.
|
|
21
|
+
* Replaces `localStorage` and `sessionStorage` with shims over the same state
|
|
22
|
+
* (keys prefixed `ls:` and `ss:`). Writes over the state limits fail in the
|
|
23
|
+
* guest before they reach the host. Talks to the host over a MessagePort, or
|
|
24
|
+
* `window.ReactNativeWebView.postMessage` in a React Native WebView.
|
|
25
|
+
*/
|
|
26
|
+
export const GUEST_BOOTSTRAP_SCRIPT = `(function(){
|
|
27
|
+
var port=null;
|
|
28
|
+
var seq=0;
|
|
29
|
+
var pending={};
|
|
30
|
+
var store=window.${ARTIFACT_SNAPSHOT_GLOBAL}&&typeof window.${ARTIFACT_SNAPSHOT_GLOBAL}==="object"?window.${ARTIFACT_SNAPSHOT_GLOBAL}:{};
|
|
31
|
+
var aliases=Array.isArray(window.${ARTIFACT_ALIASES_GLOBAL})?window.${ARTIFACT_ALIASES_GLOBAL}:[];
|
|
32
|
+
try{delete window.${ARTIFACT_SNAPSHOT_GLOBAL};delete window.${ARTIFACT_ALIASES_GLOBAL};}catch(e){}
|
|
33
|
+
function copyStore(){
|
|
34
|
+
var next={};
|
|
35
|
+
for(var k in store){if(Object.prototype.hasOwnProperty.call(store,k))next[k]=store[k];}
|
|
36
|
+
return next;
|
|
37
|
+
}
|
|
38
|
+
function utf8len(s){
|
|
39
|
+
return new TextEncoder().encode(String(s)).length;
|
|
40
|
+
}
|
|
41
|
+
function fits(data){
|
|
42
|
+
var keys=Object.keys(data);
|
|
43
|
+
if(keys.length>${String(ARTIFACT_STATE_MAX_KEYS)})return false;
|
|
44
|
+
var total=0;
|
|
45
|
+
for(var i=0;i<keys.length;i++){
|
|
46
|
+
var k=keys[i];
|
|
47
|
+
if(!k||k.length>${String(ARTIFACT_STATE_MAX_KEY_LENGTH)})return false;
|
|
48
|
+
var v=data[k];
|
|
49
|
+
if(typeof v!=="string")return false;
|
|
50
|
+
var sz=utf8len(v);
|
|
51
|
+
if(sz>${String(ARTIFACT_STATE_MAX_VALUE_BYTES)})return false;
|
|
52
|
+
total+=utf8len(k)+sz;
|
|
53
|
+
}
|
|
54
|
+
return total<=${String(ARTIFACT_STATE_MAX_TOTAL_BYTES)};
|
|
55
|
+
}
|
|
56
|
+
function send(msg){
|
|
57
|
+
if(window.ReactNativeWebView&&typeof window.ReactNativeWebView.postMessage==="function"){
|
|
58
|
+
window.ReactNativeWebView.postMessage(JSON.stringify(msg));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if(port){port.postMessage(msg);}
|
|
62
|
+
}
|
|
63
|
+
function call(op,extra){
|
|
64
|
+
return new Promise(function(resolve,reject){
|
|
65
|
+
var requestId=++seq;
|
|
66
|
+
pending[requestId]={resolve:resolve,reject:reject};
|
|
67
|
+
var msg={type:"${ARTIFACT_STATE_TYPE}",requestId:requestId,op:op};
|
|
68
|
+
if(extra){for(var k in extra){if(Object.prototype.hasOwnProperty.call(extra,k))msg[k]=extra[k];}}
|
|
69
|
+
send(msg);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function handleResult(msg){
|
|
73
|
+
var waiter=pending[msg.requestId];
|
|
74
|
+
if(!waiter)return;
|
|
75
|
+
delete pending[msg.requestId];
|
|
76
|
+
if(msg.ok)waiter.resolve(msg.value);
|
|
77
|
+
else waiter.reject(new Error(msg.error||"State error"));
|
|
78
|
+
}
|
|
79
|
+
function createStorage(prefix){
|
|
80
|
+
function names(){
|
|
81
|
+
var out=[];
|
|
82
|
+
for(var k in store){
|
|
83
|
+
if(Object.prototype.hasOwnProperty.call(store,k)&&k.indexOf(prefix)===0){
|
|
84
|
+
out.push(k.slice(prefix.length));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
var api={
|
|
90
|
+
get length(){return names().length;},
|
|
91
|
+
key:function(i){
|
|
92
|
+
var n=names();
|
|
93
|
+
return i>=0&&i<n.length?n[i]:null;
|
|
94
|
+
},
|
|
95
|
+
getItem:function(key){
|
|
96
|
+
var k=prefix+String(key);
|
|
97
|
+
return Object.prototype.hasOwnProperty.call(store,k)?store[k]:null;
|
|
98
|
+
},
|
|
99
|
+
setItem:function(key,value){
|
|
100
|
+
var k=prefix+String(key);
|
|
101
|
+
var v=String(value);
|
|
102
|
+
var next=copyStore();
|
|
103
|
+
next[k]=v;
|
|
104
|
+
if(!fits(next)){
|
|
105
|
+
throw new DOMException("The quota has been exceeded.","QuotaExceededError");
|
|
106
|
+
}
|
|
107
|
+
store=next;
|
|
108
|
+
call("set",{key:k,value:v});
|
|
109
|
+
},
|
|
110
|
+
removeItem:function(key){
|
|
111
|
+
var k=prefix+String(key);
|
|
112
|
+
if(!Object.prototype.hasOwnProperty.call(store,k))return;
|
|
113
|
+
var next=copyStore();
|
|
114
|
+
delete next[k];
|
|
115
|
+
store=next;
|
|
116
|
+
call("remove",{key:k});
|
|
117
|
+
},
|
|
118
|
+
clear:function(){
|
|
119
|
+
var n=names();
|
|
120
|
+
var next=copyStore();
|
|
121
|
+
for(var i=0;i<n.length;i++) delete next[prefix+n[i]];
|
|
122
|
+
store=next;
|
|
123
|
+
for(var j=0;j<n.length;j++) call("remove",{key:prefix+n[j]});
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
return new Proxy(api,{
|
|
127
|
+
get:function(t,p){
|
|
128
|
+
if(p in t)return t[p];
|
|
129
|
+
if(typeof p==="string")return t.getItem(p);
|
|
130
|
+
return undefined;
|
|
131
|
+
},
|
|
132
|
+
set:function(t,p,v){
|
|
133
|
+
t.setItem(String(p),String(v));
|
|
134
|
+
return true;
|
|
135
|
+
},
|
|
136
|
+
deleteProperty:function(t,p){
|
|
137
|
+
t.removeItem(String(p));
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
try{
|
|
143
|
+
Object.defineProperty(window,"localStorage",{configurable:true,enumerable:true,value:createStorage("${ARTIFACT_LOCAL_STORAGE_PREFIX}")});
|
|
144
|
+
Object.defineProperty(window,"sessionStorage",{configurable:true,enumerable:true,value:createStorage("${ARTIFACT_SESSION_STORAGE_PREFIX}")});
|
|
145
|
+
}catch(err){}
|
|
146
|
+
var state={
|
|
147
|
+
get:function(key){return call("get",{key:String(key)});},
|
|
148
|
+
set:function(key,value){
|
|
149
|
+
var encoded;
|
|
150
|
+
try{encoded=JSON.stringify(value);}
|
|
151
|
+
catch(e){return Promise.reject(e);}
|
|
152
|
+
var next=copyStore();
|
|
153
|
+
next[String(key)]=encoded;
|
|
154
|
+
if(!fits(next))return Promise.reject(new Error("State exceeds quota."));
|
|
155
|
+
store=next;
|
|
156
|
+
return call("set",{key:String(key),value:encoded});
|
|
157
|
+
},
|
|
158
|
+
getAll:function(){return call("getAll");},
|
|
159
|
+
remove:function(key){
|
|
160
|
+
var next=copyStore();
|
|
161
|
+
delete next[String(key)];
|
|
162
|
+
store=next;
|
|
163
|
+
return call("remove",{key:String(key)});
|
|
164
|
+
},
|
|
165
|
+
reset:function(){
|
|
166
|
+
store={};
|
|
167
|
+
return call("reset");
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
window.artifactState=state;
|
|
171
|
+
for(var a=0;a<aliases.length;a++){
|
|
172
|
+
if(typeof aliases[a]==="string")window[aliases[a]]={state:state};
|
|
173
|
+
}
|
|
174
|
+
window.addEventListener("message",function(event){
|
|
175
|
+
var data=event.data;
|
|
176
|
+
if(!data||typeof data!=="object")return;
|
|
177
|
+
if(data.type==="${ARTIFACT_PORT_TYPE}"&&event.ports&&event.ports[0]){
|
|
178
|
+
port=event.ports[0];
|
|
179
|
+
port.onmessage=function(e){
|
|
180
|
+
var msg=e.data;
|
|
181
|
+
if(msg&&msg.type==="${ARTIFACT_STATE_RESULT_TYPE}")handleResult(msg);
|
|
182
|
+
};
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if(data.type==="${ARTIFACT_STATE_RESULT_TYPE}")handleResult(data);
|
|
186
|
+
});
|
|
187
|
+
send({type:"${ARTIFACT_READY_TYPE}"});
|
|
188
|
+
})();`;
|
|
189
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
190
|
+
const RESERVED_ALIASES = new Set([
|
|
191
|
+
"artifactState",
|
|
192
|
+
"window",
|
|
193
|
+
"self",
|
|
194
|
+
"globalThis",
|
|
195
|
+
"document",
|
|
196
|
+
"location",
|
|
197
|
+
"top",
|
|
198
|
+
"parent",
|
|
199
|
+
"frames",
|
|
200
|
+
"localStorage",
|
|
201
|
+
"sessionStorage",
|
|
202
|
+
"ReactNativeWebView",
|
|
203
|
+
ARTIFACT_SNAPSHOT_GLOBAL,
|
|
204
|
+
ARTIFACT_ALIASES_GLOBAL,
|
|
205
|
+
]);
|
|
206
|
+
/** Throws on an alias that is not an identifier or would replace a global the page or the bootstrap needs. */
|
|
207
|
+
export function assertStateGlobalAliases(aliases) {
|
|
208
|
+
for (const alias of aliases) {
|
|
209
|
+
if (!IDENTIFIER.test(alias) || RESERVED_ALIASES.has(alias)) {
|
|
210
|
+
throw new Error(`Invalid artifact state alias: ${JSON.stringify(alias)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** JSON for an inline <script>: `<` is escaped so the data cannot close the script element. */
|
|
215
|
+
export function embedJsonInScript(value) {
|
|
216
|
+
return JSON.stringify(value).replace(/</g, "\\u003c");
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The inline script for the guest: the snapshot and aliases, then
|
|
220
|
+
* `GUEST_BOOTSTRAP_SCRIPT`. A React Native WebView can pass it as
|
|
221
|
+
* `injectedJavaScriptBeforeContentLoaded`.
|
|
222
|
+
*/
|
|
223
|
+
export function artifactGuestScript(snapshot, options = {}) {
|
|
224
|
+
const aliases = options.stateGlobalAliases ?? [];
|
|
225
|
+
assertStateGlobalAliases(aliases);
|
|
226
|
+
return (`window.${ARTIFACT_SNAPSHOT_GLOBAL}=${embedJsonInScript(snapshot ?? {})};` +
|
|
227
|
+
`window.${ARTIFACT_ALIASES_GLOBAL}=${embedJsonInScript(aliases)};` +
|
|
228
|
+
GUEST_BOOTSTRAP_SCRIPT);
|
|
229
|
+
}
|
|
230
|
+
/** Put the CSP meta tag and the guest script at the start of the document's <head>, adding a <head> or a whole document when missing. */
|
|
231
|
+
export function wrapArtifactHtml(html, snapshot, options = {}) {
|
|
232
|
+
const headInject = `<meta http-equiv="Content-Security-Policy" content="${ARTIFACT_CSP}">` +
|
|
233
|
+
`<script>${artifactGuestScript(snapshot, options)}</script>`;
|
|
234
|
+
const headMatch = html.match(/<head[^>]*>/i);
|
|
235
|
+
if (headMatch && headMatch.index !== undefined) {
|
|
236
|
+
const insertAt = headMatch.index + headMatch[0].length;
|
|
237
|
+
return html.slice(0, insertAt) + headInject + html.slice(insertAt);
|
|
238
|
+
}
|
|
239
|
+
if (/<html/i.test(html)) {
|
|
240
|
+
return html.replace(/<html[^>]*>/i, (open) => `${open}<head>${headInject}</head>`);
|
|
241
|
+
}
|
|
242
|
+
return `<!doctype html><html><head>${headInject}<meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/></head><body>${html}</body></html>`;
|
|
243
|
+
}
|