@tinacms/astro 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +37 -20
  2. package/dist/bridge-route.d.ts +3 -0
  3. package/dist/bridge-route.js +22 -0
  4. package/dist/bridge.d.ts +7 -1
  5. package/dist/bridge.js +1 -0
  6. package/dist/data.d.ts +16 -0
  7. package/dist/data.js +59 -0
  8. package/dist/experimental.d.ts +10 -0
  9. package/dist/experimental.js +57 -0
  10. package/dist/index.d.ts +36 -1
  11. package/dist/index.js +87 -2
  12. package/dist/integration.d.ts +25 -0
  13. package/dist/integration.js +22 -0
  14. package/dist/internal/escape.d.ts +8 -0
  15. package/dist/internal/forms-store.d.ts +23 -0
  16. package/dist/internal/request-context.d.ts +16 -0
  17. package/dist/is-edit-mode.d.ts +32 -0
  18. package/dist/is-edit-mode.js +37 -0
  19. package/dist/island-route.d.ts +43 -0
  20. package/dist/island-route.js +57 -0
  21. package/dist/middleware.d.ts +20 -0
  22. package/dist/middleware.js +109 -0
  23. package/dist/sanitize.d.ts +12 -1
  24. package/dist/sanitize.js +6 -10
  25. package/dist/tina-field.d.ts +1 -1
  26. package/dist/tina-field.js +1 -0
  27. package/dist/types.d.ts +92 -1
  28. package/dist/types.js +0 -1
  29. package/package.json +89 -17
  30. package/src/CodeBlockNode.astro +28 -0
  31. package/src/Container.astro +56 -0
  32. package/src/ImageNode.astro +17 -0
  33. package/src/LinkNode.astro +22 -0
  34. package/src/MdxNode.astro +24 -0
  35. package/src/Node.astro +11 -4
  36. package/src/TinaIsland.astro +42 -0
  37. package/src/TinaMarkdown.astro +8 -0
  38. package/src/__tests__/TinaMarkdown.test.ts +112 -0
  39. package/src/__tests__/__snapshots__/TinaMarkdown.test.ts.snap +7 -0
  40. package/src/__tests__/fixtures/FancyHeading.astro +3 -0
  41. package/src/__tests__/fixtures/MyFeature.astro +4 -0
  42. package/src/__tests__/fixtures/basic-kitchen-sink.json +60 -0
  43. package/src/__tests__/fixtures/code-block.json +34 -0
  44. package/src/__tests__/fixtures/leaf-marks.json +199 -0
  45. package/src/__tests__/fixtures/mdx-jsx-flow.json +40 -0
  46. package/src/__tests__/fixtures/mdx-jsx-text.json +53 -0
  47. package/src/__tests__/sanitize.test.ts +75 -0
  48. package/src/bridge-route.ts +33 -0
  49. package/src/bridge.ts +7 -0
  50. package/src/data.ts +97 -0
  51. package/src/experimental.ts +14 -0
  52. package/src/index.ts +54 -0
  53. package/src/integration.ts +49 -0
  54. package/src/internal/escape.ts +15 -0
  55. package/src/internal/forms-store.ts +41 -0
  56. package/src/internal/request-context.ts +23 -0
  57. package/src/is-edit-mode.ts +68 -0
  58. package/src/island-route.ts +110 -0
  59. package/src/middleware.ts +118 -0
  60. package/src/sanitize.ts +64 -0
  61. package/src/tina-field.ts +1 -0
  62. package/src/types.ts +97 -0
  63. package/dist/preview.d.ts +0 -1
  64. package/dist/preview.js +0 -1
package/README.md CHANGED
@@ -5,22 +5,42 @@ The one-stop [TinaCMS](https://tina.io) integration for Astro. Ships:
5
5
  - A vanilla-Astro **rich-text renderer** that mirrors the React `TinaMarkdown` API — same `content` prop, same `components` map shape, but emits pure HTML with no React in the page tree.
6
6
  - The framework-agnostic **`@tinacms/bridge`** re-exported under `@tinacms/astro/bridge` so you only install one package.
7
7
 
8
+ > **Adopting in a new project?** Follow the step-by-step [GETTING_STARTED.md](./GETTING_STARTED.md) — covers install (incl. `@tinacms/cli`), integration wiring, data loaders, island registry, and troubleshooting. The rest of this README is the API reference.
9
+
8
10
  ## Install
9
11
 
10
12
  ```bash
11
- pnpm add @tinacms/astro
13
+ pnpm add @tinacms/astro tinacms
14
+ pnpm add -D @tinacms/cli
12
15
  ```
13
16
 
14
- Requires Astro 5.
17
+ Requires Astro 5. Also needs an SSR adapter (`@astrojs/node`, `vercel`, `netlify`, or `cloudflare`) and `output: 'server'` in your Astro config.
15
18
 
16
19
  ## Usage
17
20
 
21
+ Add the integration to `astro.config.mjs` once. It wires the request-scoped middleware and the dynamic route that serves the bridge — everything else is auto-injected only on edit-mode requests:
22
+
23
+ ```ts
24
+ // astro.config.mjs
25
+ import { defineConfig } from 'astro/config';
26
+ import tina from '@tinacms/astro/integration';
27
+
28
+ export default defineConfig({
29
+ integrations: [tina()],
30
+ });
31
+ ```
32
+
33
+ Then load data the same way you would in any TinaCMS project — call the generated client, wrap the result with `requestWithMetadata()`:
34
+
18
35
  ```astro
19
36
  ---
20
- import TinaMarkdown from '@tinacms/astro';
21
- import { tinaField } from '@tinacms/astro/tina-field';
37
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
38
+ import { requestWithMetadata, tinaField } from '@tinacms/astro';
39
+ import client from '../tina/__generated__/client';
22
40
 
23
- const post = await client.queries.post({ relativePath: 'hello.md' });
41
+ const post = await requestWithMetadata(
42
+ client.queries.post({ relativePath: 'hello.md' }),
43
+ );
24
44
  ---
25
45
  <article>
26
46
  <h1 data-tina-field={tinaField(post.data.post, 'title')}>
@@ -32,28 +52,25 @@ const post = await client.queries.post({ relativePath: 'hello.md' });
32
52
  </article>
33
53
  ```
34
54
 
35
- Wire the bridge in your base layout to enable click-to-focus and live preview:
55
+ That's the whole user surface. No wiring component in your layout, no `forms` prop to maintain, no `Astro.request` to thread. The integration's middleware buffers each HTML response, and on edit-mode requests splices the form payloads and a `<script type="module" src="/_tina/bridge.js">` before `</head>`. Production visitors get **byte-identical HTML to a Tina-free Astro app** — no `data-tina-form` divs, no script tag, no bundle preload.
36
56
 
37
- ```astro
38
- <head>
39
- <script type="application/tina+json" set:html={JSON.stringify(form)} />
40
- <script>
41
- import { init } from '@tinacms/astro/bridge';
42
- init();
43
- </script>
44
- </head>
45
- ```
57
+ For cross-origin admin deployments (Codespaces, separate-domain self-hosted), set `PUBLIC_TINA_ADMIN_ORIGIN` in your env (comma-separate to allow multiple). The middleware embeds it inline so the bridge validates inbound `postMessage` events.
46
58
 
47
59
  ## Subpath exports
48
60
 
49
61
  | Subpath | What it gives you |
50
62
  |---------|-------------------|
51
- | `@tinacms/astro` | `TinaMarkdown` (default) |
63
+ | `@tinacms/astro` | `requestWithMetadata`, `tinaField`, `QueryResult`, and types |
64
+ | `@tinacms/astro/TinaMarkdown.astro` | `<TinaMarkdown content components />` — rich-text renderer. Import from this subpath so Astro's check sees a real `.astro` component (the bare-package default resolves through the types condition to a placeholder). |
65
+ | `@tinacms/astro/integration` | `tina()` integration — auto-wires middleware + bridge route so `requestWithMetadata()` works without you threading `Astro.request` or writing wiring components |
66
+ | `@tinacms/astro/TinaIsland.astro` | `<TinaIsland name wrapper params />` — marker wrapper for an editable region |
52
67
  | `@tinacms/astro/types` | `TinaRichTextContent`, `CustomComponentsMap`, `TinaRichTextNode`, `MdxElement`, `TextElement` |
53
68
  | `@tinacms/astro/sanitize` | `sanitizeHref` / `sanitizeImageSrc` for CMS-supplied URLs |
54
- | `@tinacms/astro/bridge` | `init` and the rest of `@tinacms/bridge` |
69
+ | `@tinacms/astro/bridge` | `init`, `refreshForms`, and the rest of `@tinacms/bridge` |
55
70
  | `@tinacms/astro/tina-field` | `tinaField()` helper |
56
- | `@tinacms/astro/preview` | `readOverlay()` server helper for island refresh endpoints |
71
+ | `@tinacms/astro/is-edit-mode` | `isEditMode(request)` server-side admin-iframe detection |
72
+ | `@tinacms/astro/middleware` | The middleware the integration auto-wires — exported here in case you need to compose it manually |
73
+ | `@tinacms/astro/experimental` | `experimental_createIslandRoute()` — opt-in helper built on Astro's unstable `experimental_AstroContainer` |
57
74
 
58
75
  ## Custom MDX components
59
76
 
@@ -61,7 +78,7 @@ Register Astro components against the names Tina uses for them in the editor:
61
78
 
62
79
  ```astro
63
80
  ---
64
- import TinaMarkdown from '@tinacms/astro';
81
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
65
82
  import type { CustomComponentsMap } from '@tinacms/astro/types';
66
83
  import BlockQuote from '../components/BlockQuote.astro';
67
84
  import NewsletterSignup from '../components/NewsletterSignup.astro';
@@ -99,8 +116,8 @@ The renderer doesn't emit `data-tina-field` attributes — wrap the call site to
99
116
 
100
117
  ```astro
101
118
  ---
119
+ import TinaMarkdown from '@tinacms/astro/TinaMarkdown.astro';
102
120
  import { tinaField } from '@tinacms/astro/tina-field';
103
- import TinaMarkdown from '@tinacms/astro';
104
121
  ---
105
122
  <div data-tina-field={tinaField(post.data.post, '_body')}>
106
123
  <TinaMarkdown content={post.data.post._body} components={components} />
@@ -0,0 +1,3 @@
1
+ import type { APIRoute } from 'astro';
2
+ export declare const prerender = false;
3
+ export declare const GET: APIRoute;
@@ -0,0 +1,22 @@
1
+ // src/bridge-route.ts
2
+ import { readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ var require2 = createRequire(import.meta.url);
5
+ var cached;
6
+ function loadBridge() {
7
+ if (cached !== void 0) return cached;
8
+ const bridgePath = require2.resolve("@tinacms/bridge");
9
+ cached = readFileSync(bridgePath, "utf-8");
10
+ return cached;
11
+ }
12
+ var prerender = false;
13
+ var GET = () => new Response(loadBridge(), {
14
+ headers: {
15
+ "Content-Type": "application/javascript; charset=utf-8",
16
+ "Cache-Control": "public, max-age=31536000, immutable"
17
+ }
18
+ });
19
+ export {
20
+ GET,
21
+ prerender
22
+ };
package/dist/bridge.d.ts CHANGED
@@ -1 +1,7 @@
1
- export * from "../src/bridge"
1
+ /**
2
+ * Re-exports of `@tinacms/bridge` so Astro projects can pull the bridge from
3
+ * `@tinacms/astro/bridge` instead of installing it separately. The bridge
4
+ * package stays publishable on its own for non-Astro frontends (Hugo, plain
5
+ * HTML, Eleventy).
6
+ */
7
+ export * from '@tinacms/bridge';
package/dist/bridge.js CHANGED
@@ -1 +1,2 @@
1
+ // src/bridge.ts
1
2
  export * from "@tinacms/bridge";
package/dist/data.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export interface QueryResult<TData> {
2
+ data: TData;
3
+ query: string;
4
+ variables: Record<string, unknown>;
5
+ id: string;
6
+ }
7
+ /** Shape every `client.queries.<name>` returns. Inferring from this lets
8
+ * `requestWithMetadata()` stay framework-agnostic — it doesn't need to
9
+ * know about `PostQuery`, `PageQuery`, etc. */
10
+ type ClientResult<TData> = {
11
+ data: TData;
12
+ query: string;
13
+ variables: Record<string, unknown>;
14
+ } | null | undefined;
15
+ export declare function requestWithMetadata<TData>(source: ClientResult<TData> | Promise<ClientResult<TData>>): Promise<QueryResult<TData>>;
16
+ export {};
package/dist/data.js ADDED
@@ -0,0 +1,59 @@
1
+ // src/data.ts
2
+ import { addMetadata, hashFromQuery } from "@tinacms/bridge/metadata";
3
+ import { readOverlay } from "@tinacms/bridge/preview";
4
+
5
+ // src/internal/forms-store.ts
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ var STORE_KEY = Symbol.for("@tinacms/astro/forms-store");
8
+ var slot = globalThis;
9
+ var formsStore = slot[STORE_KEY] ??= new AsyncLocalStorage();
10
+ function recordForm(form) {
11
+ const list = formsStore.getStore();
12
+ if (!list) return;
13
+ if (list.some((existing) => existing.id === form.id)) return;
14
+ list.push(form);
15
+ }
16
+
17
+ // src/internal/request-context.ts
18
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
19
+ var STORE_KEY2 = Symbol.for("@tinacms/astro/request-context");
20
+ var slot2 = globalThis;
21
+ var requestStore = slot2[STORE_KEY2] ??= new AsyncLocalStorage2();
22
+
23
+ // src/data.ts
24
+ async function requestWithMetadata(source) {
25
+ let result = null;
26
+ try {
27
+ result = await source ?? null;
28
+ } catch (error) {
29
+ console.warn("[@tinacms/astro] client query failed", error);
30
+ }
31
+ const query = result?.query ?? "";
32
+ const variables = result?.variables ?? {};
33
+ const id = hashFromQuery(JSON.stringify({ query, variables }));
34
+ const data = result?.data ?? {};
35
+ const request = requestStore.getStore();
36
+ let resolvedData = data;
37
+ if (request) {
38
+ const overlay = await readOverlay(request, id);
39
+ if (overlay !== void 0) {
40
+ resolvedData = overlay;
41
+ }
42
+ }
43
+ const enriched = {
44
+ data: addMetadata(id, resolvedData),
45
+ query,
46
+ variables,
47
+ id
48
+ };
49
+ recordForm({
50
+ id,
51
+ query,
52
+ variables,
53
+ data: enriched.data
54
+ });
55
+ return enriched;
56
+ }
57
+ export {
58
+ requestWithMetadata
59
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Experimental surface area. Anything here may change in a minor or
3
+ * patch release — opt in only when the underlying tradeoff is worth
4
+ * it for your project.
5
+ *
6
+ * `experimental_createIslandRoute` builds on Astro's
7
+ * `experimental_AstroContainer`, which Astro itself flags as unstable;
8
+ * this re-export inherits the same caveat.
9
+ */
10
+ export { experimental_createIslandRoute, type IslandConfig, type IslandRegistry, } from './island-route';
@@ -0,0 +1,57 @@
1
+ // src/island-route.ts
2
+ import { experimental_AstroContainer as AstroContainer } from "astro/container";
3
+ import { PREVIEW_CONTENT_TYPE } from "@tinacms/bridge/preview";
4
+
5
+ // src/internal/escape.ts
6
+ function escapeAttr(s) {
7
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
8
+ }
9
+
10
+ // src/island-route.ts
11
+ function experimental_createIslandRoute(islands) {
12
+ return async ({ params, request, url }) => {
13
+ const rejection = rejectIfUnsafe(request);
14
+ if (rejection) return rejection;
15
+ const island = islands[params.name ?? ""];
16
+ if (!island) {
17
+ return new Response(`Unknown island "${params.name}"`, { status: 404 });
18
+ }
19
+ try {
20
+ const data = await island.fetch(request, url.searchParams);
21
+ const container = await AstroContainer.create();
22
+ const html = await container.renderToString(island.component, {
23
+ props: island.propsFromData(data, url.searchParams)
24
+ });
25
+ return new Response(wrapIsland(html, island.wrapper, url), {
26
+ headers: {
27
+ "Content-Type": "text/html; charset=utf-8",
28
+ "Cache-Control": "no-store"
29
+ }
30
+ });
31
+ } catch {
32
+ return new Response("Island render failed", { status: 500 });
33
+ }
34
+ };
35
+ }
36
+ function rejectIfUnsafe(request) {
37
+ if (request.method !== "POST") {
38
+ return new Response("Method Not Allowed", { status: 405 });
39
+ }
40
+ const contentType = request.headers.get("content-type") ?? "";
41
+ if (!contentType.includes(PREVIEW_CONTENT_TYPE)) {
42
+ return new Response("Not Found", { status: 404 });
43
+ }
44
+ const fetchSite = request.headers.get("sec-fetch-site");
45
+ if (fetchSite === "cross-site" || fetchSite === "cross-origin") {
46
+ return new Response("Forbidden", { status: 403 });
47
+ }
48
+ return null;
49
+ }
50
+ function wrapIsland(html, wrapper, url) {
51
+ const cls = wrapper.className ? ` class="${escapeAttr(wrapper.className)}"` : "";
52
+ const marker = escapeAttr(`${url.pathname}${url.search}`);
53
+ return `<${wrapper.tag}${cls} data-tina-island="${marker}">${html}</${wrapper.tag}>`;
54
+ }
55
+ export {
56
+ experimental_createIslandRoute
57
+ };
package/dist/index.d.ts CHANGED
@@ -1 +1,36 @@
1
- export * from "../src/index"
1
+ /**
2
+ * Runtime entry for the package's `.` subpath. Astro consumers resolve
3
+ * through the `astro` export condition straight to `src/TinaMarkdown.astro`
4
+ * — they get the real component as the default export plus the named
5
+ * helpers re-exported from the .astro frontmatter.
6
+ *
7
+ * This file is the fallback for any tool that *doesn't* understand the
8
+ * `astro` condition (TypeScript types, plain Node ESM resolution). It
9
+ * exposes the named runtime helpers and a placeholder default that
10
+ * throws with a clear redirect if someone reaches it.
11
+ */
12
+ import type { AstroComponentFactory } from 'astro/runtime/server/index.js';
13
+ import type { CustomComponentsMap, TinaRichTextContent } from './types';
14
+ export { requestWithMetadata, type QueryResult } from './data';
15
+ export { tinaField } from './tina-field';
16
+ export type { AstroComponent, CustomComponentsMap, MdxElement, TextElement, TinaRichTextContent, TinaRichTextNode, TinaRichTextRoot, } from './types';
17
+ /**
18
+ * Typed shape of `<TinaMarkdown content={...} components={...} />` for tools
19
+ * that resolve through the `types` / `default` export condition rather than
20
+ * the `astro` condition. The actual component is `src/TinaMarkdown.astro`;
21
+ * this placeholder throws if invoked because the only legitimate caller is
22
+ * Astro's component pipeline, which reaches the .astro file directly.
23
+ *
24
+ * The intersection of `AstroComponentFactory` (Astro's component-validity
25
+ * check) and a typed prop signature (TinaMarkdown's actual API) gives the
26
+ * Astro language server enough shape to both recognise this as a renderable
27
+ * component AND offer prop completions / type errors at the call site.
28
+ */
29
+ type TinaMarkdownComponent = AstroComponentFactory & {
30
+ (props: {
31
+ content: TinaRichTextContent;
32
+ components?: CustomComponentsMap;
33
+ }): unknown;
34
+ };
35
+ declare const TinaMarkdownPlaceholder: TinaMarkdownComponent;
36
+ export default TinaMarkdownPlaceholder;
package/dist/index.js CHANGED
@@ -1,4 +1,89 @@
1
- const TinaMarkdown$1 = TinaMarkdown;
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+
15
+ // src/data.ts
16
+ import { addMetadata, hashFromQuery } from "@tinacms/bridge/metadata";
17
+ import { readOverlay } from "@tinacms/bridge/preview";
18
+
19
+ // src/internal/forms-store.ts
20
+ import { AsyncLocalStorage } from "node:async_hooks";
21
+ var STORE_KEY = Symbol.for("@tinacms/astro/forms-store");
22
+ var slot = globalThis;
23
+ var formsStore = slot[STORE_KEY] ??= new AsyncLocalStorage();
24
+ function recordForm(form) {
25
+ const list = formsStore.getStore();
26
+ if (!list) return;
27
+ if (list.some((existing) => existing.id === form.id)) return;
28
+ list.push(form);
29
+ }
30
+
31
+ // src/internal/request-context.ts
32
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
33
+ var STORE_KEY2 = Symbol.for("@tinacms/astro/request-context");
34
+ var slot2 = globalThis;
35
+ var requestStore = slot2[STORE_KEY2] ??= new AsyncLocalStorage2();
36
+
37
+ // src/data.ts
38
+ async function requestWithMetadata(source) {
39
+ let result = null;
40
+ try {
41
+ result = await source ?? null;
42
+ } catch (error) {
43
+ console.warn("[@tinacms/astro] client query failed", error);
44
+ }
45
+ const query = result?.query ?? "";
46
+ const variables = result?.variables ?? {};
47
+ const id = hashFromQuery(JSON.stringify({ query, variables }));
48
+ const data = result?.data ?? {};
49
+ const request = requestStore.getStore();
50
+ let resolvedData = data;
51
+ if (request) {
52
+ const overlay = await readOverlay(request, id);
53
+ if (overlay !== void 0) {
54
+ resolvedData = overlay;
55
+ }
56
+ }
57
+ const enriched = {
58
+ data: addMetadata(id, resolvedData),
59
+ query,
60
+ variables,
61
+ id
62
+ };
63
+ recordForm({
64
+ id,
65
+ query,
66
+ variables,
67
+ data: enriched.data
68
+ });
69
+ return enriched;
70
+ }
71
+
72
+ // src/tina-field.ts
73
+ var tina_field_exports = {};
74
+ __reExport(tina_field_exports, tina_field_star);
75
+ import * as tina_field_star from "@tinacms/bridge/tina-field";
76
+
77
+ // src/index.ts
78
+ var TinaMarkdownPlaceholder = () => {
79
+ throw new Error(
80
+ "[@tinacms/astro] TinaMarkdown must be loaded through Astro's pipeline. Add `tina()` from `@tinacms/astro/integration` to your astro.config integrations, or import directly from `@tinacms/astro/TinaMarkdown.astro`."
81
+ );
82
+ };
83
+ var index_default = TinaMarkdownPlaceholder;
84
+ var export_tinaField = tina_field_exports.tinaField;
2
85
  export {
3
- TinaMarkdown$1 as default
86
+ index_default as default,
87
+ requestWithMetadata,
88
+ export_tinaField as tinaField
4
89
  };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Tina Astro integration. Wires the middleware that exposes
3
+ * `Astro.locals.tinaEdit` so pages and components can branch on edit
4
+ * context without writing `src/middleware.ts` themselves.
5
+ *
6
+ * Usage:
7
+ *
8
+ * ```ts
9
+ * // astro.config.mjs
10
+ * import { defineConfig } from 'astro/config';
11
+ * import tina from '@tinacms/astro/integration';
12
+ *
13
+ * export default defineConfig({
14
+ * integrations: [tina()],
15
+ * });
16
+ * ```
17
+ */
18
+ import type { AstroIntegration } from 'astro';
19
+ export interface TinaIntegrationOptions {
20
+ /** Override the middleware ordering relative to other integrations.
21
+ * Defaults to `'pre'` so `Astro.locals.tinaEdit` is populated before
22
+ * user middleware sees the request. */
23
+ middlewareOrder?: 'pre' | 'post';
24
+ }
25
+ export default function tina(options?: TinaIntegrationOptions): AstroIntegration;
@@ -0,0 +1,22 @@
1
+ // src/integration.ts
2
+ function tina(options = {}) {
3
+ const { middlewareOrder = "pre" } = options;
4
+ return {
5
+ name: "@tinacms/astro",
6
+ hooks: {
7
+ "astro:config:setup": ({ addMiddleware, injectRoute }) => {
8
+ addMiddleware({
9
+ entrypoint: "@tinacms/astro/middleware",
10
+ order: middlewareOrder
11
+ });
12
+ injectRoute({
13
+ pattern: "/_tina/bridge.js",
14
+ entrypoint: "@tinacms/astro/bridge-route"
15
+ });
16
+ }
17
+ }
18
+ };
19
+ }
20
+ export {
21
+ tina as default
22
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * HTML attribute escape for double-quoted attributes. `&` is escaped first
3
+ * so the subsequent replacements don't double-encode existing entities.
4
+ * Adequate for the shapes we emit server-side — `data-tina-form` payloads
5
+ * and `data-tina-island` marker paths — neither of which is parsed as
6
+ * HTML downstream.
7
+ */
8
+ export declare function escapeAttr(s: string): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Per-request collector for `tina()` results. Each call pushes its
3
+ * `{id, query, variables, data}` payload here so the integration's
4
+ * middleware can read the full list at response time and splice the
5
+ * bridge wiring into edit-mode pages — the user never writes a `forms`
6
+ * prop or imports a wiring component.
7
+ *
8
+ * Initialised by the middleware the `tina()` integration injects.
9
+ *
10
+ * The store is keyed by a `Symbol.for(...)` slot on `globalThis` so all
11
+ * bundle copies of this module (esbuild inlines it into each entry that
12
+ * imports it) share the same instance — without that, the middleware
13
+ * would `.run()` one ALS while `tina()` reads from a different one.
14
+ */
15
+ import { AsyncLocalStorage } from 'node:async_hooks';
16
+ export interface CollectedForm {
17
+ id: string;
18
+ query: string;
19
+ variables: object;
20
+ data: object;
21
+ }
22
+ export declare const formsStore: AsyncLocalStorage<CollectedForm[]>;
23
+ export declare function recordForm(form: CollectedForm): void;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Request-scoped storage so `tina()` can read the current request without
3
+ * the caller threading `Astro.request` through every loader. The
4
+ * middleware injected by the `tina()` integration runs every request
5
+ * through `requestStore.run(...)`.
6
+ *
7
+ * Falls through to `undefined` outside a request scope (static builds,
8
+ * integration not installed) — `tina()` treats that as "no overlay,
9
+ * no edit mode," so static contexts still produce correct output.
10
+ *
11
+ * Stashed on `globalThis` via `Symbol.for(...)` so all bundle copies of
12
+ * this module share one ALS instance — esbuild inlines it into every
13
+ * entry that imports it, and per-entry copies wouldn't share state.
14
+ */
15
+ import { AsyncLocalStorage } from 'node:async_hooks';
16
+ export declare const requestStore: AsyncLocalStorage<Request>;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Server-side check: is this request being rendered inside the TinaCMS
3
+ * admin iframe?
4
+ *
5
+ * Resolves true when any of the following hold:
6
+ * 1. `?tina-edit=1` — explicit signal added by the admin's router for
7
+ * deep-link previews.
8
+ * 2. `Sec-Fetch-Dest: iframe` AND a same-origin Referer under
9
+ * `/admin/` — covers the first request after the admin sets
10
+ * `iframe.src` to a preview URL.
11
+ * 3. `Sec-Fetch-Dest: iframe` AND a `__tina_edit=1` cookie — covers
12
+ * in-iframe link clicks, where the Referer is the previous preview
13
+ * page rather than `/admin/`. The middleware sets the cookie on
14
+ * every edit-mode response so the session sticks for the iframe's
15
+ * lifetime.
16
+ *
17
+ * Direct browser visits set `Sec-Fetch-Dest: document` for top-level
18
+ * navigations, so a stale cookie left behind in someone's browser can
19
+ * never trip edit mode outside an iframe — production HTML is byte-
20
+ * identical to a Tina-free Astro app for end users.
21
+ */
22
+ export declare const EDIT_COOKIE = "__tina_edit";
23
+ /**
24
+ * Set-Cookie header value the middleware writes on every edit-mode
25
+ * response. Refreshing on each response keeps long editing sessions
26
+ * sticky and short Max-Age limits the blast radius if a cookie lingers.
27
+ * The `Sec-Fetch-Dest: iframe` gate in `isEditMode` blocks the cookie
28
+ * from triggering edit mode on top-level visits.
29
+ */
30
+ export declare const EDIT_COOKIE_HEADER = "__tina_edit=1; Path=/; SameSite=Strict; Max-Age=3600";
31
+ export declare function isEditMode(request: Request): boolean;
32
+ export declare function readCookie(request: Request, name: string): string | null;
@@ -0,0 +1,37 @@
1
+ // src/is-edit-mode.ts
2
+ var EDIT_COOKIE = "__tina_edit";
3
+ var EDIT_COOKIE_HEADER = `${EDIT_COOKIE}=1; Path=/; SameSite=Strict; Max-Age=3600`;
4
+ function isEditMode(request) {
5
+ const url = new URL(request.url);
6
+ if (url.searchParams.get("tina-edit") === "1") return true;
7
+ const dest = request.headers.get("Sec-Fetch-Dest");
8
+ if (dest !== "iframe") return false;
9
+ const referer = request.headers.get("Referer");
10
+ if (referer) {
11
+ try {
12
+ const refererUrl = new URL(referer);
13
+ if (refererUrl.origin === url.origin && refererUrl.pathname.startsWith("/admin/")) {
14
+ return true;
15
+ }
16
+ } catch {
17
+ }
18
+ }
19
+ return readCookie(request, EDIT_COOKIE) === "1";
20
+ }
21
+ function readCookie(request, name) {
22
+ const header = request.headers.get("Cookie");
23
+ if (!header) return null;
24
+ for (const pair of header.split(";")) {
25
+ const eq = pair.indexOf("=");
26
+ if (eq === -1) continue;
27
+ const key = pair.slice(0, eq).trim();
28
+ if (key === name) return pair.slice(eq + 1).trim();
29
+ }
30
+ return null;
31
+ }
32
+ export {
33
+ EDIT_COOKIE,
34
+ EDIT_COOKIE_HEADER,
35
+ isEditMode,
36
+ readCookie
37
+ };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Factory for the dynamic `/tina-island/[name]` endpoint the bridge calls
3
+ * to refetch a region with the editor's overlay applied. Each entry in
4
+ * `islands` describes one editable region: how to load its data, which
5
+ * Astro component to render, and the wrapper element the page-side
6
+ * `<div data-tina-island>` is expected to swap.
7
+ *
8
+ * @experimental
9
+ *
10
+ * Built on Astro's `experimental_AstroContainer`, which is itself
11
+ * experimental — Astro may break the underlying API in any minor or patch
12
+ * release. The shape of `createIslandRoute` is similarly experimental and
13
+ * will graduate once the container API stabilises.
14
+ *
15
+ * Usage:
16
+ *
17
+ * ```ts
18
+ * // src/pages/tina-island/[name].ts
19
+ * import { experimental_createIslandRoute } from '@tinacms/astro/experimental';
20
+ * import { islands } from '../../lib/islands';
21
+ *
22
+ * export const prerender = false;
23
+ * export const ALL = experimental_createIslandRoute(islands);
24
+ * ```
25
+ */
26
+ import type { APIRoute } from 'astro';
27
+ import type { AstroComponentFactory } from 'astro/runtime/server/index.js';
28
+ export interface IslandWrapper {
29
+ tag: string;
30
+ className?: string;
31
+ }
32
+ export interface IslandConfig {
33
+ /** Resolve the data the component needs. May ignore the search params. */
34
+ fetch: (request: Request, params: URLSearchParams) => Promise<unknown>;
35
+ /** Astro component to render with the fetched data. */
36
+ component: AstroComponentFactory;
37
+ /** Outer element the bridge swaps into — must match the page-side wrapper. */
38
+ wrapper: IslandWrapper;
39
+ /** Map fetched data + URL params to the component's props. */
40
+ propsFromData: (data: unknown, params: URLSearchParams) => Record<string, unknown>;
41
+ }
42
+ export type IslandRegistry = Record<string, IslandConfig>;
43
+ export declare function experimental_createIslandRoute(islands: IslandRegistry): APIRoute;