@nodehive/nextjs 0.3.0 → 0.5.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 (43) hide show
  1. package/dist/auth/internal/draft-session.d.ts +12 -0
  2. package/dist/auth/internal/draft-session.js +22 -0
  3. package/dist/auth/internal/draft-session.js.map +1 -0
  4. package/dist/auth/internal/refresh.d.ts +10 -0
  5. package/dist/auth/internal/refresh.js +17 -0
  6. package/dist/auth/internal/refresh.js.map +1 -1
  7. package/dist/auth/internal/update-session.js +2 -1
  8. package/dist/auth/internal/update-session.js.map +1 -1
  9. package/dist/auth/server.d.ts +1 -0
  10. package/dist/auth/server.js +1 -0
  11. package/dist/auth/server.js.map +1 -1
  12. package/dist/puck-editor/internal/api/config.d.ts +10 -0
  13. package/dist/puck-editor/internal/api/config.js.map +1 -1
  14. package/dist/puck-editor/internal/api/create-puck-api.js +16 -2
  15. package/dist/puck-editor/internal/api/create-puck-api.js.map +1 -1
  16. package/dist/puck-editor/internal/api/handlers/schema.d.ts +6 -0
  17. package/dist/puck-editor/internal/api/handlers/schema.js +41 -0
  18. package/dist/puck-editor/internal/api/handlers/schema.js.map +1 -0
  19. package/dist/puck-editor/internal/fields/checkbox-group/create-checkbox-group-field.d.ts +5 -0
  20. package/dist/puck-editor/internal/fields/checkbox-group/create-checkbox-group-field.js +5 -0
  21. package/dist/puck-editor/internal/fields/checkbox-group/create-checkbox-group-field.js.map +1 -1
  22. package/dist/puck-editor/internal/fields/date-picker/create-date-picker-field.d.ts +5 -0
  23. package/dist/puck-editor/internal/fields/date-picker/create-date-picker-field.js +5 -0
  24. package/dist/puck-editor/internal/fields/date-picker/create-date-picker-field.js.map +1 -1
  25. package/dist/puck-editor/internal/fields/link-picker/create-link-field.d.ts +5 -0
  26. package/dist/puck-editor/internal/fields/link-picker/create-link-field.js +5 -0
  27. package/dist/puck-editor/internal/fields/link-picker/create-link-field.js.map +1 -1
  28. package/dist/puck-editor/internal/fields/media-array/create-media-array-field.d.ts +3 -0
  29. package/dist/puck-editor/internal/fields/media-array/create-media-array-field.js +3 -0
  30. package/dist/puck-editor/internal/fields/media-array/create-media-array-field.js.map +1 -1
  31. package/dist/puck-editor/internal/fields/media-selector/create-media-selector-field.d.ts +3 -0
  32. package/dist/puck-editor/internal/fields/media-selector/create-media-selector-field.js +3 -0
  33. package/dist/puck-editor/internal/fields/media-selector/create-media-selector-field.js.map +1 -1
  34. package/dist/puck-editor/internal/fields/node-selector/create-node-selector-field.d.ts +5 -0
  35. package/dist/puck-editor/internal/fields/node-selector/create-node-selector-field.js +5 -0
  36. package/dist/puck-editor/internal/fields/node-selector/create-node-selector-field.js.map +1 -1
  37. package/dist/puck-editor/internal/schema.d.ts +28 -0
  38. package/dist/puck-editor/internal/schema.js +83 -0
  39. package/dist/puck-editor/internal/schema.js.map +1 -0
  40. package/dist/puck-editor/server.d.ts +1 -0
  41. package/dist/puck-editor/server.js +1 -0
  42. package/dist/puck-editor/server.js.map +1 -1
  43. package/package.json +1 -1
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The predicate for the data layer's draft-vs-cached branch. The draft cookie
3
+ * alone is not enough: it survives its session (see clearStaleDraftCookie), and
4
+ * taking the draft branch without a token means fetching as a user that is not
5
+ * there. Without a session this returns false and the caller falls back to the
6
+ * cached anonymous branch, which is what the visitor gets anyway.
7
+ *
8
+ * isEnabled must stay the first operand. draftMode() is prerender-safe (false
9
+ * at build time) while a cookie read is not, so the short-circuit is what keeps
10
+ * the anonymous branch inside the static shell under cacheComponents.
11
+ */
12
+ export declare const isDraftSession: () => Promise<boolean>;
@@ -0,0 +1,22 @@
1
+ import { cache } from 'react';
2
+ import { draftMode } from 'next/headers';
3
+ import { checkHasSession } from "./has-session.js";
4
+
5
+ /**
6
+ * The predicate for the data layer's draft-vs-cached branch. The draft cookie
7
+ * alone is not enough: it survives its session (see clearStaleDraftCookie), and
8
+ * taking the draft branch without a token means fetching as a user that is not
9
+ * there. Without a session this returns false and the caller falls back to the
10
+ * cached anonymous branch, which is what the visitor gets anyway.
11
+ *
12
+ * isEnabled must stay the first operand. draftMode() is prerender-safe (false
13
+ * at build time) while a cookie read is not, so the short-circuit is what keeps
14
+ * the anonymous branch inside the static shell under cacheComponents.
15
+ */
16
+ export const isDraftSession = cache(async () => {
17
+ const {
18
+ isEnabled
19
+ } = await draftMode();
20
+ return isEnabled && (await checkHasSession());
21
+ });
22
+ //# sourceMappingURL=draft-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"draft-session.js","names":["cache","draftMode","checkHasSession","isDraftSession","isEnabled"],"sources":["../../../src/auth/internal/draft-session.ts"],"sourcesContent":["import { cache } from 'react';\nimport { draftMode } from 'next/headers';\n\nimport { checkHasSession } from './has-session.ts';\n\n/**\n * The predicate for the data layer's draft-vs-cached branch. The draft cookie\n * alone is not enough: it survives its session (see clearStaleDraftCookie), and\n * taking the draft branch without a token means fetching as a user that is not\n * there. Without a session this returns false and the caller falls back to the\n * cached anonymous branch, which is what the visitor gets anyway.\n *\n * isEnabled must stay the first operand. draftMode() is prerender-safe (false\n * at build time) while a cookie read is not, so the short-circuit is what keeps\n * the anonymous branch inside the static shell under cacheComponents.\n */\nexport const isDraftSession = cache(async (): Promise<boolean> => {\n const { isEnabled } = await draftMode();\n return isEnabled && (await checkHasSession());\n});\n"],"mappings":"AAAA,SAASA,KAAK,QAAQ,OAAO;AAC7B,SAASC,SAAS,QAAQ,cAAc;AAExC,SAASC,eAAe,QAAQ,kBAAkB;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,cAAc,GAAGH,KAAK,CAAC,YAA8B;EAChE,MAAM;IAAEI;EAAU,CAAC,GAAG,MAAMH,SAAS,CAAC,CAAC;EACvC,OAAOG,SAAS,KAAK,MAAMF,eAAe,CAAC,CAAC,CAAC;AAC/C,CAAC,CAAC","ignoreList":[]}
@@ -9,4 +9,14 @@ export declare function shouldRefreshSession(request: NextRequest): boolean;
9
9
  */
10
10
  export declare function refreshSession(request: NextRequest, response: NextResponse, config: NodeHiveAuthConfig): Promise<void>;
11
11
  export declare function clearAuthCookies(request: NextRequest, response: NextResponse): void;
12
+ /**
13
+ * clearAuthCookies takes the draft cookie down with the session, but it only
14
+ * runs once a refresh was attempted and rejected. When the refresh-token cookie
15
+ * is simply gone there is nothing to refresh, shouldRefreshSession bails out,
16
+ * and a draft cookie from an earlier login outlives its session — it is set for
17
+ * the full refresh-token lifetime, so this can last weeks. The data layer then
18
+ * reads draftMode() as enabled and fetches with a user client that has no
19
+ * token, which is answered with Drupal's HTML error pages.
20
+ */
21
+ export declare function clearStaleDraftCookie(request: NextRequest, response: NextResponse): void;
12
22
  export declare function isAuthFailure(error: unknown): boolean;
@@ -93,6 +93,23 @@ export function clearAuthCookies(request, response) {
93
93
  }
94
94
  }
95
95
 
96
+ /**
97
+ * clearAuthCookies takes the draft cookie down with the session, but it only
98
+ * runs once a refresh was attempted and rejected. When the refresh-token cookie
99
+ * is simply gone there is nothing to refresh, shouldRefreshSession bails out,
100
+ * and a draft cookie from an earlier login outlives its session — it is set for
101
+ * the full refresh-token lifetime, so this can last weeks. The data layer then
102
+ * reads draftMode() as enabled and fetches with a user client that has no
103
+ * token, which is answered with Drupal's HTML error pages.
104
+ */
105
+ export function clearStaleDraftCookie(request, response) {
106
+ const keys = NextCookieStorage.cookieKeys();
107
+ if (request.cookies.get(keys.refresh_token)) return;
108
+ if (!request.cookies.get(DRAFT_MODE_COOKIE)) return;
109
+ request.cookies.delete(DRAFT_MODE_COOKIE);
110
+ appendClearedAuthCookie(response, DRAFT_MODE_COOKIE);
111
+ }
112
+
96
113
  // Auth failure (invalid/expired refresh token) vs transient (network, timeout,
97
114
  // 5xx): transient errors keep the session, auth failures clear it.
98
115
  export function isAuthFailure(error) {
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.js","names":["AuthenticationError","DRAFT_MODE_COOKIE","appendClearedAuthCookie","NextCookieStorage","buildUserClient","REFRESH_TOKEN_MAX_AGE","MAX_RETRIES","BACKOFF_MS","ROTATION_GRACE_MS","refreshDeadlineMs","setRefreshDeadlineMsForTesting","ms","wait","Promise","resolve","setTimeout","withDeadline","promise","race","_","reject","timer","Error","unref","activeRefreshes","Map","recentRotations","rememberRotation","oldToken","result","expiresAt","Date","now","set","delete","getRecentRotation","entry","get","console","info","shouldRefreshSession","request","keys","cookieKeys","token","cookies","value","refreshToken","refresh_token","token_expires_at","expiresAtNumber","Number","tokenExpiresSoon","isFinite","refreshSession","response","config","refreshOnce","clearAuthCookies","name","Object","values","isAuthFailure","error","status","details","applyLoginResult","context","storage","maxAge","expires_in","undefined","tokenOptions","String","user","JSON","stringify","recent","existing","then","client","underlying","refreshWithRetries","finally","lastError","attempt","auth","warn"],"sources":["../../../src/auth/internal/refresh.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\nimport { AuthenticationError, type LoginResult } from 'nodehive-js';\n\nimport type { NodeHiveAuthConfig } from './config.ts';\nimport { DRAFT_MODE_COOKIE } from './draft-mode.ts';\nimport {\n appendClearedAuthCookie,\n NextCookieStorage,\n type ProxyContext,\n} from './next-cookie-storage.ts';\nimport { buildUserClient } from './nodehive-client.ts';\nimport { REFRESH_TOKEN_MAX_AGE } from './oauth-config.ts';\n\nconst MAX_RETRIES = 3;\nconst BACKOFF_MS = 200;\nconst ROTATION_GRACE_MS = 30_000;\n// Hard ceiling for a whole refresh (incl. retries). The proxy awaits this on\n// nearly every request, and the SDK's token fetch has no timeout of its own, so\n// without this a slow/hung Drupal would stall every page load. On timeout the\n// error is non-auth → treated as transient → the stale session is kept.\nlet refreshDeadlineMs = 5_000;\n\nexport function setRefreshDeadlineMsForTesting(ms: number) {\n refreshDeadlineMs = ms;\n}\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n const timer = setTimeout(\n () => reject(new Error('Token refresh timed out')),\n ms\n );\n timer.unref?.();\n }),\n ]);\n}\n\n// Per-user dedup: prevents concurrent requests from racing on token rotation.\n// Note: This Map is per-isolate — on serverless deployments, dedup is best-effort\n// and not guaranteed across concurrent isolates. On long-running servers it works fully.\nconst activeRefreshes = new Map<string, Promise<LoginResult>>();\n\n// Grace cache for recently rotated refresh tokens.\n//\n// OAuth refresh tokens are single-use: each successful refresh invalidates the\n// previous one. But the browser can have parallel requests in flight carrying\n// the old refresh-token cookie when the rotation happens. Without this cache,\n// stale requests arriving just AFTER the original refresh completed (so the\n// `activeRefreshes` dedup map is already empty) trigger a second refresh that\n// fails with invalid_grant and logs the user out.\n//\n// Mapping: old refresh_token → fresh LoginResult, valid for ROTATION_GRACE_MS.\nconst recentRotations = new Map<\n string,\n { result: LoginResult; expiresAt: number }\n>();\n\nfunction rememberRotation(oldToken: string, result: LoginResult) {\n const expiresAt = Date.now() + ROTATION_GRACE_MS;\n recentRotations.set(oldToken, { result, expiresAt });\n setTimeout(\n () => recentRotations.delete(oldToken),\n ROTATION_GRACE_MS\n ).unref?.();\n}\n\nfunction getRecentRotation(oldToken: string): LoginResult | null {\n const entry = recentRotations.get(oldToken);\n if (!entry) return null;\n if (entry.expiresAt < Date.now()) {\n recentRotations.delete(oldToken);\n return null;\n }\n console.info('[Refresh] grace cache hit — stale refresh-token reused');\n return entry.result;\n}\n\nexport function shouldRefreshSession(request: NextRequest): boolean {\n const keys = NextCookieStorage.cookieKeys();\n const token = request.cookies.get(keys.token)?.value;\n const refreshToken = request.cookies.get(keys.refresh_token)?.value;\n const expiresAt = request.cookies.get(keys.token_expires_at)?.value;\n\n if (!refreshToken) return false;\n\n const expiresAtNumber = expiresAt ? Number(expiresAt) : null;\n const tokenExpiresSoon =\n typeof expiresAtNumber === 'number' &&\n Number.isFinite(expiresAtNumber) &&\n expiresAtNumber <= Date.now() + 60_000;\n\n return !token || tokenExpiresSoon;\n}\n\n/**\n * Mutates request.cookies and sets Set-Cookie on `response`; the caller must\n * have created `response` with `{ request }` so the mutations are forwarded via\n * x-middleware-request-* headers. Throws on failure — caller decides handling.\n */\nexport async function refreshSession(\n request: NextRequest,\n response: NextResponse,\n config: NodeHiveAuthConfig\n): Promise<void> {\n const keys = NextCookieStorage.cookieKeys();\n const refreshToken = request.cookies.get(keys.refresh_token)?.value;\n\n if (!refreshToken) {\n throw new AuthenticationError('No refresh token available');\n }\n\n await refreshOnce(refreshToken, { request, response }, config);\n}\n\nexport function clearAuthCookies(\n request: NextRequest,\n response: NextResponse\n): void {\n const keys = NextCookieStorage.cookieKeys();\n // Draft cookie included: a dead session must not strand the visitor in\n // token-less draft mode. Raw headers — middleware cannot call draftMode().\n for (const name of [...Object.values(keys), DRAFT_MODE_COOKIE]) {\n request.cookies.delete(name);\n appendClearedAuthCookie(response, name);\n }\n}\n\n// Auth failure (invalid/expired refresh token) vs transient (network, timeout,\n// 5xx): transient errors keep the session, auth failures clear it.\nexport function isAuthFailure(error: unknown): boolean {\n if (!(error instanceof AuthenticationError)) return false;\n const status = error.details?.status;\n return status === 400 || status === 401 || status === 403;\n}\n\n// When the refresh is served from the grace cache or an in-flight dedup, the SDK\n// never ran for THIS request, so its cookies were never written. Mirror the\n// tokens onto the current request/response so this navigation renders logged-in\n// and the browser receives the fresh cookies.\nasync function applyLoginResult(\n context: ProxyContext,\n result: LoginResult\n): Promise<LoginResult> {\n const storage = new NextCookieStorage(context);\n const maxAge = result.expires_in ?? undefined;\n const tokenOptions = maxAge ? { maxAge } : undefined;\n\n await storage.set('token', result.token, tokenOptions);\n if (result.refresh_token) {\n await storage.set('refresh_token', result.refresh_token, {\n maxAge: REFRESH_TOKEN_MAX_AGE,\n });\n }\n if (maxAge) {\n await storage.set(\n 'token_expires_at',\n String(Date.now() + maxAge * 1000),\n tokenOptions\n );\n }\n if (result.user) {\n await storage.set(\n 'user_details',\n typeof result.user === 'string'\n ? result.user\n : JSON.stringify(result.user),\n tokenOptions\n );\n }\n return result;\n}\n\nfunction refreshOnce(\n refreshToken: string,\n context: ProxyContext,\n config: NodeHiveAuthConfig\n): Promise<LoginResult> {\n const recent = getRecentRotation(refreshToken);\n if (recent) return applyLoginResult(context, recent);\n\n const existing = activeRefreshes.get(refreshToken);\n if (existing) {\n return withDeadline(\n existing.then((result) => applyLoginResult(context, result)),\n refreshDeadlineMs\n );\n }\n\n const client = buildUserClient(config, context);\n\n // rememberRotation and the dedup cleanup hang off the underlying refresh, NOT\n // the deadline-raced promise: if Drupal answers after the deadline the\n // refresh token is already consumed, so it must still be grace-cached or the\n // next request gets invalid_grant.\n const underlying = refreshWithRetries(client)\n .then((result) => {\n rememberRotation(refreshToken, result);\n return result;\n })\n .finally(() => {\n activeRefreshes.delete(refreshToken);\n });\n\n activeRefreshes.set(refreshToken, underlying);\n return withDeadline(underlying, refreshDeadlineMs);\n}\n\nasync function refreshWithRetries(\n client: ReturnType<typeof buildUserClient>\n): Promise<LoginResult> {\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n try {\n return await client.auth.refreshToken();\n } catch (error) {\n lastError = error;\n\n // Don't retry auth failures (invalid/expired refresh token)\n if (isAuthFailure(error)) {\n throw error;\n }\n\n if (attempt < MAX_RETRIES) {\n console.warn(`[Refresh] Attempt ${attempt} failed, retrying...`, error);\n await wait(BACKOFF_MS * 2 ** (attempt - 1));\n }\n }\n }\n\n throw lastError;\n}\n"],"mappings":"AACA,SAASA,mBAAmB,QAA0B,aAAa;AAGnE,SAASC,iBAAiB,QAAQ,iBAAiB;AACnD,SACEC,uBAAuB,EACvBC,iBAAiB,QAEZ,0BAA0B;AACjC,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,qBAAqB,QAAQ,mBAAmB;AAEzD,MAAMC,WAAW,GAAG,CAAC;AACrB,MAAMC,UAAU,GAAG,GAAG;AACtB,MAAMC,iBAAiB,GAAG,MAAM;AAChC;AACA;AACA;AACA;AACA,IAAIC,iBAAiB,GAAG,KAAK;AA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AAO,CAAC,MAAM;IACb3D,eAAe,CAACU,MAAM,CAACa,YAAY,CAAC;EACtC,CAAC,CAAC;EAEJvB,eAAe,CAACS,GAAG,CAACc,YAAY,EAAEkC,UAAU,CAAC;EAC7C,OAAOjE,YAAY,CAACiE,UAAU,EAAExE,iBAAiB,CAAC;AACpD;AAEA,eAAeyE,kBAAkBA,CAC/BF,MAA0C,EACpB;EACtB,IAAII,SAAkB;EAEtB,KAAK,IAAIC,OAAO,GAAG,CAAC,EAAEA,OAAO,IAAI/E,WAAW,EAAE+E,OAAO,EAAE,EAAE;IACvD,IAAI;MACF,OAAO,MAAML,MAAM,CAACM,IAAI,CAACvC,YAAY,CAAC,CAAC;IACzC,CAAC,CAAC,OAAOgB,KAAK,EAAE;MACdqB,SAAS,GAAGrB,KAAK;;MAEjB;MACA,IAAID,aAAa,CAACC,KAAK,CAAC,EAAE;QACxB,MAAMA,KAAK;MACb;MAEA,IAAIsB,OAAO,GAAG/E,WAAW,EAAE;QACzBgC,OAAO,CAACiD,IAAI,CAAC,qBAAqBF,OAAO,sBAAsB,EAAEtB,KAAK,CAAC;QACvE,MAAMnD,IAAI,CAACL,UAAU,GAAG,CAAC,KAAK8E,OAAO,GAAG,CAAC,CAAC,CAAC;MAC7C;IACF;EACF;EAEA,MAAMD,SAAS;AACjB","ignoreList":[]}
1
+ {"version":3,"file":"refresh.js","names":["AuthenticationError","DRAFT_MODE_COOKIE","appendClearedAuthCookie","NextCookieStorage","buildUserClient","REFRESH_TOKEN_MAX_AGE","MAX_RETRIES","BACKOFF_MS","ROTATION_GRACE_MS","refreshDeadlineMs","setRefreshDeadlineMsForTesting","ms","wait","Promise","resolve","setTimeout","withDeadline","promise","race","_","reject","timer","Error","unref","activeRefreshes","Map","recentRotations","rememberRotation","oldToken","result","expiresAt","Date","now","set","delete","getRecentRotation","entry","get","console","info","shouldRefreshSession","request","keys","cookieKeys","token","cookies","value","refreshToken","refresh_token","token_expires_at","expiresAtNumber","Number","tokenExpiresSoon","isFinite","refreshSession","response","config","refreshOnce","clearAuthCookies","name","Object","values","clearStaleDraftCookie","isAuthFailure","error","status","details","applyLoginResult","context","storage","maxAge","expires_in","undefined","tokenOptions","String","user","JSON","stringify","recent","existing","then","client","underlying","refreshWithRetries","finally","lastError","attempt","auth","warn"],"sources":["../../../src/auth/internal/refresh.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\nimport { AuthenticationError, type LoginResult } from 'nodehive-js';\n\nimport type { NodeHiveAuthConfig } from './config.ts';\nimport { DRAFT_MODE_COOKIE } from './draft-mode.ts';\nimport {\n appendClearedAuthCookie,\n NextCookieStorage,\n type ProxyContext,\n} from './next-cookie-storage.ts';\nimport { buildUserClient } from './nodehive-client.ts';\nimport { REFRESH_TOKEN_MAX_AGE } from './oauth-config.ts';\n\nconst MAX_RETRIES = 3;\nconst BACKOFF_MS = 200;\nconst ROTATION_GRACE_MS = 30_000;\n// Hard ceiling for a whole refresh (incl. retries). The proxy awaits this on\n// nearly every request, and the SDK's token fetch has no timeout of its own, so\n// without this a slow/hung Drupal would stall every page load. On timeout the\n// error is non-auth → treated as transient → the stale session is kept.\nlet refreshDeadlineMs = 5_000;\n\nexport function setRefreshDeadlineMsForTesting(ms: number) {\n refreshDeadlineMs = ms;\n}\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n const timer = setTimeout(\n () => reject(new Error('Token refresh timed out')),\n ms\n );\n timer.unref?.();\n }),\n ]);\n}\n\n// Per-user dedup: prevents concurrent requests from racing on token rotation.\n// Note: This Map is per-isolate — on serverless deployments, dedup is best-effort\n// and not guaranteed across concurrent isolates. On long-running servers it works fully.\nconst activeRefreshes = new Map<string, Promise<LoginResult>>();\n\n// Grace cache for recently rotated refresh tokens.\n//\n// OAuth refresh tokens are single-use: each successful refresh invalidates the\n// previous one. But the browser can have parallel requests in flight carrying\n// the old refresh-token cookie when the rotation happens. Without this cache,\n// stale requests arriving just AFTER the original refresh completed (so the\n// `activeRefreshes` dedup map is already empty) trigger a second refresh that\n// fails with invalid_grant and logs the user out.\n//\n// Mapping: old refresh_token → fresh LoginResult, valid for ROTATION_GRACE_MS.\nconst recentRotations = new Map<\n string,\n { result: LoginResult; expiresAt: number }\n>();\n\nfunction rememberRotation(oldToken: string, result: LoginResult) {\n const expiresAt = Date.now() + ROTATION_GRACE_MS;\n recentRotations.set(oldToken, { result, expiresAt });\n setTimeout(\n () => recentRotations.delete(oldToken),\n ROTATION_GRACE_MS\n ).unref?.();\n}\n\nfunction getRecentRotation(oldToken: string): LoginResult | null {\n const entry = recentRotations.get(oldToken);\n if (!entry) return null;\n if (entry.expiresAt < Date.now()) {\n recentRotations.delete(oldToken);\n return null;\n }\n console.info('[Refresh] grace cache hit — stale refresh-token reused');\n return entry.result;\n}\n\nexport function shouldRefreshSession(request: NextRequest): boolean {\n const keys = NextCookieStorage.cookieKeys();\n const token = request.cookies.get(keys.token)?.value;\n const refreshToken = request.cookies.get(keys.refresh_token)?.value;\n const expiresAt = request.cookies.get(keys.token_expires_at)?.value;\n\n if (!refreshToken) return false;\n\n const expiresAtNumber = expiresAt ? Number(expiresAt) : null;\n const tokenExpiresSoon =\n typeof expiresAtNumber === 'number' &&\n Number.isFinite(expiresAtNumber) &&\n expiresAtNumber <= Date.now() + 60_000;\n\n return !token || tokenExpiresSoon;\n}\n\n/**\n * Mutates request.cookies and sets Set-Cookie on `response`; the caller must\n * have created `response` with `{ request }` so the mutations are forwarded via\n * x-middleware-request-* headers. Throws on failure — caller decides handling.\n */\nexport async function refreshSession(\n request: NextRequest,\n response: NextResponse,\n config: NodeHiveAuthConfig\n): Promise<void> {\n const keys = NextCookieStorage.cookieKeys();\n const refreshToken = request.cookies.get(keys.refresh_token)?.value;\n\n if (!refreshToken) {\n throw new AuthenticationError('No refresh token available');\n }\n\n await refreshOnce(refreshToken, { request, response }, config);\n}\n\nexport function clearAuthCookies(\n request: NextRequest,\n response: NextResponse\n): void {\n const keys = NextCookieStorage.cookieKeys();\n // Draft cookie included: a dead session must not strand the visitor in\n // token-less draft mode. Raw headers — middleware cannot call draftMode().\n for (const name of [...Object.values(keys), DRAFT_MODE_COOKIE]) {\n request.cookies.delete(name);\n appendClearedAuthCookie(response, name);\n }\n}\n\n/**\n * clearAuthCookies takes the draft cookie down with the session, but it only\n * runs once a refresh was attempted and rejected. When the refresh-token cookie\n * is simply gone there is nothing to refresh, shouldRefreshSession bails out,\n * and a draft cookie from an earlier login outlives its session — it is set for\n * the full refresh-token lifetime, so this can last weeks. The data layer then\n * reads draftMode() as enabled and fetches with a user client that has no\n * token, which is answered with Drupal's HTML error pages.\n */\nexport function clearStaleDraftCookie(\n request: NextRequest,\n response: NextResponse\n): void {\n const keys = NextCookieStorage.cookieKeys();\n if (request.cookies.get(keys.refresh_token)) return;\n if (!request.cookies.get(DRAFT_MODE_COOKIE)) return;\n\n request.cookies.delete(DRAFT_MODE_COOKIE);\n appendClearedAuthCookie(response, DRAFT_MODE_COOKIE);\n}\n\n// Auth failure (invalid/expired refresh token) vs transient (network, timeout,\n// 5xx): transient errors keep the session, auth failures clear it.\nexport function isAuthFailure(error: unknown): boolean {\n if (!(error instanceof AuthenticationError)) return false;\n const status = error.details?.status;\n return status === 400 || status === 401 || status === 403;\n}\n\n// When the refresh is served from the grace cache or an in-flight dedup, the SDK\n// never ran for THIS request, so its cookies were never written. Mirror the\n// tokens onto the current request/response so this navigation renders logged-in\n// and the browser receives the fresh cookies.\nasync function applyLoginResult(\n context: ProxyContext,\n result: LoginResult\n): Promise<LoginResult> {\n const storage = new NextCookieStorage(context);\n const maxAge = result.expires_in ?? undefined;\n const tokenOptions = maxAge ? { maxAge } : undefined;\n\n await storage.set('token', result.token, tokenOptions);\n if (result.refresh_token) {\n await storage.set('refresh_token', result.refresh_token, {\n maxAge: REFRESH_TOKEN_MAX_AGE,\n });\n }\n if (maxAge) {\n await storage.set(\n 'token_expires_at',\n String(Date.now() + maxAge * 1000),\n tokenOptions\n );\n }\n if (result.user) {\n await storage.set(\n 'user_details',\n typeof result.user === 'string'\n ? result.user\n : JSON.stringify(result.user),\n tokenOptions\n );\n }\n return result;\n}\n\nfunction refreshOnce(\n refreshToken: string,\n context: ProxyContext,\n config: NodeHiveAuthConfig\n): Promise<LoginResult> {\n const recent = getRecentRotation(refreshToken);\n if (recent) return applyLoginResult(context, recent);\n\n const existing = activeRefreshes.get(refreshToken);\n if (existing) {\n return withDeadline(\n existing.then((result) => applyLoginResult(context, result)),\n refreshDeadlineMs\n );\n }\n\n const client = buildUserClient(config, context);\n\n // rememberRotation and the dedup cleanup hang off the underlying refresh, NOT\n // the deadline-raced promise: if Drupal answers after the deadline the\n // refresh token is already consumed, so it must still be grace-cached or the\n // next request gets invalid_grant.\n const underlying = refreshWithRetries(client)\n .then((result) => {\n rememberRotation(refreshToken, result);\n return result;\n })\n .finally(() => {\n activeRefreshes.delete(refreshToken);\n });\n\n activeRefreshes.set(refreshToken, underlying);\n return withDeadline(underlying, refreshDeadlineMs);\n}\n\nasync function refreshWithRetries(\n client: ReturnType<typeof buildUserClient>\n): Promise<LoginResult> {\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n try {\n return await client.auth.refreshToken();\n } catch (error) {\n lastError = error;\n\n // Don't retry auth failures (invalid/expired refresh token)\n if (isAuthFailure(error)) {\n throw error;\n }\n\n if (attempt < MAX_RETRIES) {\n console.warn(`[Refresh] Attempt ${attempt} failed, retrying...`, error);\n await wait(BACKOFF_MS * 2 ** (attempt - 1));\n }\n }\n }\n\n throw lastError;\n}\n"],"mappings":"AACA,SAASA,mBAAmB,QAA0B,aAAa;AAGnE,SAASC,iBAAiB,QAAQ,iBAAiB;AACnD,SACEC,uBAAuB,EACvBC,iBAAiB,QAEZ,0BAA0B;AACjC,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,qBAAqB,QAAQ,mBAAm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CAACkD,IAAI,CAAC,qBAAqBF,OAAO,sBAAsB,EAAEtB,KAAK,CAAC;QACvE,MAAMpD,IAAI,CAACL,UAAU,GAAG,CAAC,KAAK+E,OAAO,GAAG,CAAC,CAAC,CAAC;MAC7C;IACF;EACF;EAEA,MAAMD,SAAS;AACjB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import { isAuthFailure, refreshSession, shouldRefreshSession } from "./refresh.js";
1
+ import { clearStaleDraftCookie, isAuthFailure, refreshSession, shouldRefreshSession } from "./refresh.js";
2
2
  /**
3
3
  * Silent token refresh for the middleware (Supabase `updateSession` pattern).
4
4
  * Owns the prefetch shortcut + shouldRefresh decision. Mutates request.cookies
@@ -15,6 +15,7 @@ export async function updateSession(request, response, config) {
15
15
  };
16
16
  }
17
17
  if (!shouldRefreshSession(request)) {
18
+ clearStaleDraftCookie(request, response);
18
19
  return {
19
20
  authFailed: false
20
21
  };
@@ -1 +1 @@
1
- {"version":3,"file":"update-session.js","names":["isAuthFailure","refreshSession","shouldRefreshSession","updateSession","request","response","config","headers","get","authFailed","error","console","warn"],"sources":["../../../src/auth/internal/update-session.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\n\nimport type { NodeHiveAuthConfig } from './config.ts';\nimport {\n isAuthFailure,\n refreshSession,\n shouldRefreshSession,\n} from './refresh.ts';\n\nexport interface UpdateSessionResult {\n /** Refresh token invalid/expired — caller must clear cookies and start a fresh\n * login. Caller builds the response (401 for /api, redirect for pages). */\n authFailed: boolean;\n}\n\n/**\n * Silent token refresh for the middleware (Supabase `updateSession` pattern).\n * Owns the prefetch shortcut + shouldRefresh decision. Mutates request.cookies\n * and sets Set-Cookie on `response` (caller must create it with `{ request }`).\n *\n * Returns authFailed as DATA, not a response: the 401-vs-redirect choice needs\n * isApi + the public origin, which are proxy.ts's concern.\n */\nexport async function updateSession(\n request: NextRequest,\n response: NextResponse,\n config: NodeHiveAuthConfig\n): Promise<UpdateSessionResult> {\n // A Next prefetch must never consume the single-use refresh token.\n if (request.headers.get('next-router-prefetch') === '1') {\n return { authFailed: false };\n }\n\n if (!shouldRefreshSession(request)) {\n return { authFailed: false };\n }\n\n try {\n await refreshSession(request, response, config);\n return { authFailed: false };\n } catch (error) {\n if (isAuthFailure(error)) {\n return { authFailed: true };\n }\n\n console.warn(\n '[nodehive-auth] Token refresh failed (transient), keeping session:',\n error\n );\n return { authFailed: false };\n }\n}\n"],"mappings":"AAGA,SACEA,aAAa,EACbC,cAAc,EACdC,oBAAoB,QACf,cAAc;AAQrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,aAAaA,CACjCC,OAAoB,EACpBC,QAAsB,EACtBC,MAA0B,EACI;EAC9B;EACA,IAAIF,OAAO,CAACG,OAAO,CAACC,GAAG,CAAC,sBAAsB,CAAC,KAAK,GAAG,EAAE;IACvD,OAAO;MAAEC,UAAU,EAAE;IAAM,CAAC;EAC9B;EAEA,IAAI,CAACP,oBAAoB,CAACE,OAAO,CAAC,EAAE;IAClC,OAAO;MAAEK,UAAU,EAAE;IAAM,CAAC;EAC9B;EAEA,IAAI;IACF,MAAMR,cAAc,CAACG,OAAO,EAAEC,QAAQ,EAAEC,MAAM,CAAC;IAC/C,OAAO;MAAEG,UAAU,EAAE;IAAM,CAAC;EAC9B,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,IAAIV,aAAa,CAACU,KAAK,CAAC,EAAE;MACxB,OAAO;QAAED,UAAU,EAAE;MAAK,CAAC;IAC7B;IAEAE,OAAO,CAACC,IAAI,CACV,oEAAoE,EACpEF,KACF,CAAC;IACD,OAAO;MAAED,UAAU,EAAE;IAAM,CAAC;EAC9B;AACF","ignoreList":[]}
1
+ {"version":3,"file":"update-session.js","names":["clearStaleDraftCookie","isAuthFailure","refreshSession","shouldRefreshSession","updateSession","request","response","config","headers","get","authFailed","error","console","warn"],"sources":["../../../src/auth/internal/update-session.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\n\nimport type { NodeHiveAuthConfig } from './config.ts';\nimport {\n clearStaleDraftCookie,\n isAuthFailure,\n refreshSession,\n shouldRefreshSession,\n} from './refresh.ts';\n\nexport interface UpdateSessionResult {\n /** Refresh token invalid/expired — caller must clear cookies and start a fresh\n * login. Caller builds the response (401 for /api, redirect for pages). */\n authFailed: boolean;\n}\n\n/**\n * Silent token refresh for the middleware (Supabase `updateSession` pattern).\n * Owns the prefetch shortcut + shouldRefresh decision. Mutates request.cookies\n * and sets Set-Cookie on `response` (caller must create it with `{ request }`).\n *\n * Returns authFailed as DATA, not a response: the 401-vs-redirect choice needs\n * isApi + the public origin, which are proxy.ts's concern.\n */\nexport async function updateSession(\n request: NextRequest,\n response: NextResponse,\n config: NodeHiveAuthConfig\n): Promise<UpdateSessionResult> {\n // A Next prefetch must never consume the single-use refresh token.\n if (request.headers.get('next-router-prefetch') === '1') {\n return { authFailed: false };\n }\n\n if (!shouldRefreshSession(request)) {\n clearStaleDraftCookie(request, response);\n return { authFailed: false };\n }\n\n try {\n await refreshSession(request, response, config);\n return { authFailed: false };\n } catch (error) {\n if (isAuthFailure(error)) {\n return { authFailed: true };\n }\n\n console.warn(\n '[nodehive-auth] Token refresh failed (transient), keeping session:',\n error\n );\n return { authFailed: false };\n }\n}\n"],"mappings":"AAGA,SACEA,qBAAqB,EACrBC,aAAa,EACbC,cAAc,EACdC,oBAAoB,QACf,cAAc;AAQrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,aAAaA,CACjCC,OAAoB,EACpBC,QAAsB,EACtBC,MAA0B,EACI;EAC9B;EACA,IAAIF,OAAO,CAACG,OAAO,CAACC,GAAG,CAAC,sBAAsB,CAAC,KAAK,GAAG,EAAE;IACvD,OAAO;MAAEC,UAAU,EAAE;IAAM,CAAC;EAC9B;EAEA,IAAI,CAACP,oBAAoB,CAACE,OAAO,CAAC,EAAE;IAClCL,qBAAqB,CAACK,OAAO,EAAEC,QAAQ,CAAC;IACxC,OAAO;MAAEI,UAAU,EAAE;IAAM,CAAC;EAC9B;EAEA,IAAI;IACF,MAAMR,cAAc,CAACG,OAAO,EAAEC,QAAQ,EAAEC,MAAM,CAAC;IAC/C,OAAO;MAAEG,UAAU,EAAE;IAAM,CAAC;EAC9B,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,IAAIV,aAAa,CAACU,KAAK,CAAC,EAAE;MACxB,OAAO;QAAED,UAAU,EAAE;MAAK,CAAC;IAC7B;IAEAE,OAAO,CAACC,IAAI,CACV,oEAAoE,EACpEF,KACF,CAAC;IACD,OAAO;MAAED,UAAU,EAAE;IAAM,CAAC;EAC9B;AACF","ignoreList":[]}
@@ -14,6 +14,7 @@ export declare function createNodeHiveAuth(config: NodeHiveAuthConfig): {
14
14
  performLogout: (options?: PerformLogoutOptions) => Promise<void>;
15
15
  };
16
16
  export { shouldEnableDraftMode } from './internal/draft-mode.js';
17
+ export { isDraftSession } from './internal/draft-session.js';
17
18
  export { checkHasSession } from './internal/has-session.js';
18
19
  export { getEditorLocale, resolveEditorLocale, } from './internal/editor-locale.js';
19
20
  export { requireAuth } from './internal/require-auth.js';
@@ -57,6 +57,7 @@ export function createNodeHiveAuth(config) {
57
57
  };
58
58
  }
59
59
  export { shouldEnableDraftMode } from "./internal/draft-mode.js";
60
+ export { isDraftSession } from "./internal/draft-session.js";
60
61
  export { checkHasSession } from "./internal/has-session.js";
61
62
  export { getEditorLocale, resolveEditorLocale } from "./internal/editor-locale.js";
62
63
  export { requireAuth } from "./internal/require-auth.js";
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["cache","checkHasSession","performLogout","NextCookieStorage","buildAnonClient","buildUserClient","createNodeHiveAuth","config","createUserClient","proxyContext","preventSdkRefresh","anonClient","createAnonClient","createClient","storage","token","get","isAuthenticated","options","shouldEnableDraftMode","getEditorLocale","resolveEditorLocale","requireAuth","getUserRoles","isSameOriginRequest","SignedIn","SignedOut"],"sources":["../../src/auth/server.ts"],"sourcesContent":["// Server entry: client factories, editor guard, logout.\nimport { cache } from 'react';\n\nimport type { NodeHiveAuthConfig } from './internal/config.ts';\nimport { checkHasSession } from './internal/has-session.ts';\nimport { performLogout, type PerformLogoutOptions } from './internal/logout.ts';\nimport {\n NextCookieStorage,\n type ProxyContext,\n} from './internal/next-cookie-storage.ts';\nimport {\n buildAnonClient,\n buildUserClient,\n} from './internal/nodehive-client.ts';\n\n/**\n * Bind the client factories + logout to a project config (explicit injection,\n * no global singleton). Call once in the project and re-export the result.\n */\nexport function createNodeHiveAuth(config: NodeHiveAuthConfig) {\n /**\n * Deliberately act as the logged-in user. Default: use createClient().\n * Binds to the request's session cookies but guarantees no user: without a\n * session the client carries no token (it is NOT the anon client) — use it\n * only where a session is established or where you check isLoggedIn().\n */\n const createUserClient = (proxyContext?: ProxyContext) =>\n buildUserClient(config, proxyContext, { preventSdkRefresh: !proxyContext });\n\n /**\n * Deliberately act as an anonymous visitor (client_credentials, capped\n * rights). Default: use createClient(). One instance per runtime since the\n * credential never rotates.\n */\n let anonClient: ReturnType<typeof buildAnonClient> | null = null;\n const createAnonClient = () => {\n if (anonClient) return anonClient;\n anonClient = buildAnonClient(config);\n return anonClient;\n };\n\n /**\n * The default client: user client when a usable access token is present,\n * else the anon client. Memoized per request via React cache().\n *\n * Checks the short-lived access token, not the refresh token: only the\n * proxy may refresh (rotated tokens can't be persisted from RSCs), so the\n * user client is only picked when a request-ready token exists. \"Is the\n * user logged in?\" is a different question — that's isAuthenticated, which\n * checks the durable refresh token.\n */\n const createClient = cache(async () => {\n const storage = new NextCookieStorage();\n const token = await storage.get('token');\n return token ? createUserClient() : createAnonClient();\n });\n\n const isAuthenticated = cache(checkHasSession);\n\n return {\n createClient,\n createUserClient,\n createAnonClient,\n isAuthenticated,\n performLogout: (options?: PerformLogoutOptions) =>\n performLogout(config, options),\n };\n}\n\nexport { shouldEnableDraftMode } from './internal/draft-mode.ts';\nexport { checkHasSession } from './internal/has-session.ts';\nexport {\n getEditorLocale,\n resolveEditorLocale,\n} from './internal/editor-locale.ts';\nexport { requireAuth } from './internal/require-auth.ts';\nexport { getUserRoles } from './internal/roles.ts';\nexport { isSameOriginRequest } from './internal/same-origin.ts';\nexport { SignedIn, SignedOut } from './internal/session-gates.tsx';\nexport type { NodeHiveAuthConfig } from './internal/config.ts';\nexport type { ProxyContext } from './internal/next-cookie-storage.ts';\nexport type { PerformLogoutOptions } from './internal/logout.ts';\n"],"mappings":"AAAA;AACA,SAASA,KAAK,QAAQ,OAAO;AAG7B,SAASC,eAAe,QAAQ,2BAA2B;AAC3D,SAASC,aAAa,QAAmC,sBAAsB;AAC/E,SACEC,iBAAiB,QAEZ,mCAAmC;AAC1C,SACEC,eAAe,EACfC,eAAe,QACV,+BAA+B;;AAEtC;AACA;AACA;AACA;AACA,OAAO,SAASC,kBAAkBA,CAACC,MAA0B,EAAE;EAC7D;AACF;AACA;AACA;AACA;AACA;EACE,MAAMC,gBAAgB,GAAIC,YAA2B,IACnDJ,eAAe,CAACE,MAAM,EAAEE,YAAY,EAAE;IAAEC,iBAAiB,EAAE,CAACD;EAAa,CAAC,CAAC;;EAE7E;AACF;AACA;AACA;AACA;EACE,IAAIE,UAAqD,GAAG,IAAI;EAChE,MAAMC,gBAAgB,GAAGA,CAAA,KAAM;IAC7B,IAAID,UAAU,EAAE,OAAOA,UAAU;IACjCA,UAAU,GAAGP,eAAe,CAACG,MAAM,CAAC;IACpC,OAAOI,UAAU;EACnB,CAAC;;EAED;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,MAAME,YAAY,GAAGb,KAAK,CAAC,YAAY;IACrC,MAAMc,OAAO,GAAG,IAAIX,iBAAiB,CAAC,CAAC;IACvC,MAAMY,KAAK,GAAG,MAAMD,OAAO,CAACE,GAAG,CAAC,OAAO,CAAC;IACxC,OAAOD,KAAK,GAAGP,gBAAgB,CAAC,CAAC,GAAGI,gBAAgB,CAAC,CAAC;EACxD,CAAC,CAAC;EAEF,MAAMK,eAAe,GAAGjB,KAAK,CAACC,eAAe,CAAC;EAE9C,OAAO;IACLY,YAAY;IACZL,gBAAgB;IAChBI,gBAAgB;IAChBK,eAAe;IACff,aAAa,EAAGgB,OAA8B,IAC5ChB,aAAa,CAACK,MAAM,EAAEW,OAAO;EACjC,CAAC;AACH;AAEA,SAASC,qBAAqB,QAAQ,0BAA0B;AAChE,SAASlB,eAAe,QAAQ,2BAA2B;AAC3D,SACEmB,eAAe,EACfC,mBAAmB,QACd,6BAA6B;AACpC,SAASC,WAAW,QAAQ,4BAA4B;AACxD,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,mBAAmB,QAAQ,2BAA2B;AAC/D,SAASC,QAAQ,EAAEC,SAAS,QAAQ,6BAA8B","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["cache","checkHasSession","performLogout","NextCookieStorage","buildAnonClient","buildUserClient","createNodeHiveAuth","config","createUserClient","proxyContext","preventSdkRefresh","anonClient","createAnonClient","createClient","storage","token","get","isAuthenticated","options","shouldEnableDraftMode","isDraftSession","getEditorLocale","resolveEditorLocale","requireAuth","getUserRoles","isSameOriginRequest","SignedIn","SignedOut"],"sources":["../../src/auth/server.ts"],"sourcesContent":["// Server entry: client factories, editor guard, logout.\nimport { cache } from 'react';\n\nimport type { NodeHiveAuthConfig } from './internal/config.ts';\nimport { checkHasSession } from './internal/has-session.ts';\nimport { performLogout, type PerformLogoutOptions } from './internal/logout.ts';\nimport {\n NextCookieStorage,\n type ProxyContext,\n} from './internal/next-cookie-storage.ts';\nimport {\n buildAnonClient,\n buildUserClient,\n} from './internal/nodehive-client.ts';\n\n/**\n * Bind the client factories + logout to a project config (explicit injection,\n * no global singleton). Call once in the project and re-export the result.\n */\nexport function createNodeHiveAuth(config: NodeHiveAuthConfig) {\n /**\n * Deliberately act as the logged-in user. Default: use createClient().\n * Binds to the request's session cookies but guarantees no user: without a\n * session the client carries no token (it is NOT the anon client) — use it\n * only where a session is established or where you check isLoggedIn().\n */\n const createUserClient = (proxyContext?: ProxyContext) =>\n buildUserClient(config, proxyContext, { preventSdkRefresh: !proxyContext });\n\n /**\n * Deliberately act as an anonymous visitor (client_credentials, capped\n * rights). Default: use createClient(). One instance per runtime since the\n * credential never rotates.\n */\n let anonClient: ReturnType<typeof buildAnonClient> | null = null;\n const createAnonClient = () => {\n if (anonClient) return anonClient;\n anonClient = buildAnonClient(config);\n return anonClient;\n };\n\n /**\n * The default client: user client when a usable access token is present,\n * else the anon client. Memoized per request via React cache().\n *\n * Checks the short-lived access token, not the refresh token: only the\n * proxy may refresh (rotated tokens can't be persisted from RSCs), so the\n * user client is only picked when a request-ready token exists. \"Is the\n * user logged in?\" is a different question — that's isAuthenticated, which\n * checks the durable refresh token.\n */\n const createClient = cache(async () => {\n const storage = new NextCookieStorage();\n const token = await storage.get('token');\n return token ? createUserClient() : createAnonClient();\n });\n\n const isAuthenticated = cache(checkHasSession);\n\n return {\n createClient,\n createUserClient,\n createAnonClient,\n isAuthenticated,\n performLogout: (options?: PerformLogoutOptions) =>\n performLogout(config, options),\n };\n}\n\nexport { shouldEnableDraftMode } from './internal/draft-mode.ts';\nexport { isDraftSession } from './internal/draft-session.ts';\nexport { checkHasSession } from './internal/has-session.ts';\nexport {\n getEditorLocale,\n resolveEditorLocale,\n} from './internal/editor-locale.ts';\nexport { requireAuth } from './internal/require-auth.ts';\nexport { getUserRoles } from './internal/roles.ts';\nexport { isSameOriginRequest } from './internal/same-origin.ts';\nexport { SignedIn, SignedOut } from './internal/session-gates.tsx';\nexport type { NodeHiveAuthConfig } from './internal/config.ts';\nexport type { ProxyContext } from './internal/next-cookie-storage.ts';\nexport type { PerformLogoutOptions } from './internal/logout.ts';\n"],"mappings":"AAAA;AACA,SAASA,KAAK,QAAQ,OAAO;AAG7B,SAASC,eAAe,QAAQ,2BAA2B;AAC3D,SAASC,aAAa,QAAmC,sBAAsB;AAC/E,SACEC,iBAAiB,QAEZ,mCAAmC;AAC1C,SACEC,eAAe,EACfC,eAAe,QACV,+BAA+B;;AAEtC;AACA;AACA;AAC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A8B","ignoreList":[]}
@@ -1,4 +1,5 @@
1
1
  import type { NextRequest, NextResponse } from 'next/server';
2
+ import type { Config } from '@puckeditor/core';
2
3
  import type { NodeHiveClient } from 'nodehive-js';
3
4
  import type { PuckContentModel, PuckContentModelInput } from '../content-model.js';
4
5
  import type { RoutableLink } from '../fields/link-picker/types.js';
@@ -55,6 +56,15 @@ export type PuckApiConfig = {
55
56
  * upload limit). Pass the same value to the client's PuckEditorConfig.
56
57
  */
57
58
  contentModel?: PuckContentModelInput;
59
+ /**
60
+ * Server-safe Puck Config per bundle type. Enables GET /schema, which
61
+ * exports the component structure for backend consumers (search indexing,
62
+ * translation). The endpoint is served without auth so a Drupal backend can
63
+ * fetch it server-to-server; the response exposes component and prop names,
64
+ * their semantic kinds, each bundle's Drupal data field machine name, and
65
+ * generator warnings.
66
+ */
67
+ puckConfigs?: Record<string, Config>;
58
68
  };
59
69
  /** Config plus the resolved content model, as handed to the handlers. */
60
70
  export type PuckApiRuntime = PuckApiConfig & {
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../../../src/puck-editor/internal/api/config.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\nimport type { NodeHiveClient } from 'nodehive-js';\n\nimport type {\n PuckContentModel,\n PuckContentModelInput,\n} from '../content-model.ts';\nimport type { RoutableLink } from '../fields/link-picker/types.ts';\n\nexport type PuckPublishPageSettings = {\n title?: string;\n metadataTitle?: string;\n metadataDescription?: string;\n metadataImage?: {\n id?: string;\n type?: string;\n name?: string;\n thumbnailImage?: string;\n } | null;\n published?: boolean;\n urlAlias?: string;\n};\n\nexport type PuckPublishPayload = {\n path?: string;\n type: string;\n data: unknown;\n nodeId: string;\n fieldName: string;\n lang?: string;\n pageSettings?: PuckPublishPageSettings;\n};\n\nexport type PuckPublishContext = {\n request: NextRequest;\n model: PuckContentModel;\n createUserClient: () => NodeHiveClient;\n};\n\nexport type PuckApiConfig = {\n /** Default client: user when a session token is present, else anon. */\n createClient: () => Promise<NodeHiveClient> | NodeHiveClient;\n /** Client that deliberately acts as the logged-in user. */\n createUserClient: () => NodeHiveClient;\n /** NodeHive space new pages and templates are assigned to. */\n spaceId?: string;\n /** Internally-routable pages offered by the link picker. */\n getLinks?: (lang: string) => Promise<RoutableLink[]>;\n /**\n * Called before the publish write. Return the (optionally mutated) payload to\n * continue, or a NextResponse to abort the publish with that response (e.g. a\n * 4xx for custom validation or business rules).\n */\n onBeforePublish?: (\n payload: PuckPublishPayload,\n ctx: PuckPublishContext\n ) =>\n | PuckPublishPayload\n | NextResponse\n | Promise<PuckPublishPayload | NextResponse>;\n /** Called after a successful publish, e.g. for project cache-tag invalidation. */\n onPublished?: (info: {\n nodeId: string;\n path?: string;\n lang?: string;\n }) => void | Promise<void>;\n /**\n * Drupal content-model overrides (puck-enabled bundles, templates, media\n * upload limit). Pass the same value to the client's PuckEditorConfig.\n */\n contentModel?: PuckContentModelInput;\n};\n\n/** Config plus the resolved content model, as handed to the handlers. */\nexport type PuckApiRuntime = PuckApiConfig & { model: PuckContentModel };\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../../../src/puck-editor/internal/api/config.ts"],"sourcesContent":["import type { NextRequest, NextResponse } from 'next/server';\nimport type { Config } from '@puckeditor/core';\nimport type { NodeHiveClient } from 'nodehive-js';\n\nimport type {\n PuckContentModel,\n PuckContentModelInput,\n} from '../content-model.ts';\nimport type { RoutableLink } from '../fields/link-picker/types.ts';\n\nexport type PuckPublishPageSettings = {\n title?: string;\n metadataTitle?: string;\n metadataDescription?: string;\n metadataImage?: {\n id?: string;\n type?: string;\n name?: string;\n thumbnailImage?: string;\n } | null;\n published?: boolean;\n urlAlias?: string;\n};\n\nexport type PuckPublishPayload = {\n path?: string;\n type: string;\n data: unknown;\n nodeId: string;\n fieldName: string;\n lang?: string;\n pageSettings?: PuckPublishPageSettings;\n};\n\nexport type PuckPublishContext = {\n request: NextRequest;\n model: PuckContentModel;\n createUserClient: () => NodeHiveClient;\n};\n\nexport type PuckApiConfig = {\n /** Default client: user when a session token is present, else anon. */\n createClient: () => Promise<NodeHiveClient> | NodeHiveClient;\n /** Client that deliberately acts as the logged-in user. */\n createUserClient: () => NodeHiveClient;\n /** NodeHive space new pages and templates are assigned to. */\n spaceId?: string;\n /** Internally-routable pages offered by the link picker. */\n getLinks?: (lang: string) => Promise<RoutableLink[]>;\n /**\n * Called before the publish write. Return the (optionally mutated) payload to\n * continue, or a NextResponse to abort the publish with that response (e.g. a\n * 4xx for custom validation or business rules).\n */\n onBeforePublish?: (\n payload: PuckPublishPayload,\n ctx: PuckPublishContext\n ) =>\n | PuckPublishPayload\n | NextResponse\n | Promise<PuckPublishPayload | NextResponse>;\n /** Called after a successful publish, e.g. for project cache-tag invalidation. */\n onPublished?: (info: {\n nodeId: string;\n path?: string;\n lang?: string;\n }) => void | Promise<void>;\n /**\n * Drupal content-model overrides (puck-enabled bundles, templates, media\n * upload limit). Pass the same value to the client's PuckEditorConfig.\n */\n contentModel?: PuckContentModelInput;\n /**\n * Server-safe Puck Config per bundle type. Enables GET /schema, which\n * exports the component structure for backend consumers (search indexing,\n * translation). The endpoint is served without auth so a Drupal backend can\n * fetch it server-to-server; the response exposes component and prop names,\n * their semantic kinds, each bundle's Drupal data field machine name, and\n * generator warnings.\n */\n puckConfigs?: Record<string, Config>;\n};\n\n/** Config plus the resolved content model, as handed to the handlers. */\nexport type PuckApiRuntime = PuckApiConfig & { model: PuckContentModel };\n"],"mappings":"","ignoreList":[]}
@@ -5,6 +5,7 @@ import { normalizeLang } from "../locale.js";
5
5
  import { handleCreatePage } from "./handlers/create-page.js";
6
6
  import { handleFragmentList, handleLinks, handleMediaItem, handleMediaList, handleNodeItem, handleNodeList } from "./handlers/entities.js";
7
7
  import { handlePublish } from "./handlers/publish.js";
8
+ import { handleSchema } from "./handlers/schema.js";
8
9
  import { handleDeleteTemplate, handleSaveTemplate, handleUpdateTemplate } from "./handlers/template.js";
9
10
  import { handleUpload } from "./handlers/upload.js";
10
11
  import { isValidTypeSegment } from "./type-segment.js";
@@ -25,6 +26,21 @@ export function createPuckApi(rawConfig) {
25
26
  model: resolveContentModel(rawConfig.contentModel)
26
27
  };
27
28
  const handle = async (request, context) => {
29
+ const segments = (await context.params).puck ?? [];
30
+ const [resource, second, third] = segments;
31
+ if (request.method === 'GET' && resource === 'schema' && segments.length === 1) {
32
+ try {
33
+ return handleSchema(config);
34
+ } catch (error) {
35
+ console.error('puck api GET /schema:', error);
36
+ return NextResponse.json({
37
+ status: 'error',
38
+ message: 'An unexpected error occurred'
39
+ }, {
40
+ status: 500
41
+ });
42
+ }
43
+ }
28
44
  const unauthorized = await requireAuth();
29
45
  if (unauthorized) return unauthorized;
30
46
  if (request.method !== 'GET' && !isSameOriginRequest(request)) {
@@ -35,8 +51,6 @@ export function createPuckApi(rawConfig) {
35
51
  status: 403
36
52
  });
37
53
  }
38
- const segments = (await context.params).puck ?? [];
39
- const [resource, second, third] = segments;
40
54
  const {
41
55
  searchParams
42
56
  } = request.nextUrl;
@@ -1 +1 @@
1
- {"version":3,"file":"create-puck-api.js","names":["NextResponse","isSameOriginRequest","requireAuth","resolveContentModel","normalizeLang","handleCreatePage","handleFragmentList","handleLinks","handleMediaItem","handleMediaList","handleNodeItem","handleNodeList","handlePublish","handleDeleteTemplate","handleSaveTemplate","handleUpdateTemplate","handleUpload","isValidTypeSegment","createPuckApi","rawConfig","config","model","contentModel","handle","request","context","unauthorized","method","json","status","message","segments","params","puck","resource","second","third","searchParams","nextUrl","lang","get","typedResources","Set","has","error","length","console","join","GET","POST","PATCH","DELETE"],"sources":["../../../../src/puck-editor/internal/api/create-puck-api.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\n\nimport { isSameOriginRequest, requireAuth } from '../../../auth/server.ts';\nimport { resolveContentModel } from '../content-model.ts';\nimport { normalizeLang } from '../locale.ts';\nimport type { PuckApiConfig, PuckApiRuntime } from './config.ts';\nimport { handleCreatePage } from './handlers/create-page.ts';\nimport {\n handleFragmentList,\n handleLinks,\n handleMediaItem,\n handleMediaList,\n handleNodeItem,\n handleNodeList,\n} from './handlers/entities.ts';\nimport { handlePublish } from './handlers/publish.ts';\nimport {\n handleDeleteTemplate,\n handleSaveTemplate,\n handleUpdateTemplate,\n} from './handlers/template.ts';\nimport { handleUpload } from './handlers/upload.ts';\nimport { isValidTypeSegment } from './type-segment.ts';\n\ntype PuckRouteContext = { params: Promise<{ puck?: string[] }> };\n\n/**\n * Handler factory for the Puck editor backend, mounted once as a catch-all\n * route (Auth.js pattern):\n *\n * // src/app/api/puck/[...puck]/route.ts\n * export const { GET, POST, PATCH, DELETE } = createPuckApi({ ... });\n *\n * Projects extend via Next.js routing precedence, not via config: a sibling\n * route file next to the mount adds an endpoint, a file on the same path as a\n * built-in handler shadows it.\n */\nexport function createPuckApi(rawConfig: PuckApiConfig) {\n const config: PuckApiRuntime = {\n ...rawConfig,\n model: resolveContentModel(rawConfig.contentModel),\n };\n const handle = async (request: NextRequest, context: PuckRouteContext) => {\n const unauthorized = await requireAuth();\n if (unauthorized) return unauthorized;\n\n if (request.method !== 'GET' && !isSameOriginRequest(request)) {\n return NextResponse.json(\n { status: 'error', message: 'cross-site request rejected' },\n { status: 403 }\n );\n }\n\n const segments = (await context.params).puck ?? [];\n const [resource, second, third] = segments;\n const { searchParams } = request.nextUrl;\n const lang = normalizeLang(searchParams.get('lang'));\n\n const typedResources = new Set(['node', 'media', 'fragment']);\n if (typedResources.has(resource) && !isValidTypeSegment(second)) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n }\n\n try {\n switch (request.method) {\n case 'GET':\n if (resource === 'links' && segments.length === 1) {\n return await handleLinks(config, lang);\n }\n if (resource === 'node' && segments.length === 2) {\n return await handleNodeList(config, second, searchParams);\n }\n if (resource === 'node' && segments.length === 3) {\n return await handleNodeItem(config, second, third, lang);\n }\n if (resource === 'media' && segments.length === 2) {\n return await handleMediaList(config, second, searchParams);\n }\n if (resource === 'media' && segments.length === 3) {\n return await handleMediaItem(config, second, third, lang);\n }\n if (resource === 'fragment' && segments.length === 2) {\n return await handleFragmentList(config, second, searchParams);\n }\n break;\n case 'POST':\n if (resource === 'create' && segments.length === 1) {\n return await handleCreatePage(config, request);\n }\n if (resource === 'upload' && segments.length === 1) {\n return await handleUpload(config, request);\n }\n if (resource === 'template' && segments.length === 1) {\n return await handleSaveTemplate(config, request);\n }\n break;\n case 'PATCH':\n if (resource === 'publish' && segments.length === 1) {\n return await handlePublish(config, request);\n }\n if (resource === 'template' && segments.length === 3) {\n return await handleUpdateTemplate(config, second, third, request);\n }\n break;\n case 'DELETE':\n if (resource === 'template' && segments.length === 3) {\n return await handleDeleteTemplate(config, second, third);\n }\n break;\n }\n } catch (error) {\n console.error(\n `puck api ${request.method} /${segments.join('/')}:`,\n error\n );\n return NextResponse.json(\n { status: 'error', message: 'An unexpected error occurred' },\n { status: 500 }\n );\n }\n\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n };\n\n return { GET: handle, POST: handle, PATCH: handle, DELETE: handle };\n}\n"],"mappings":"AAAA,SAAsBA,YAAY,QAAQ,aAAa;AAEvD,SAASC,mBAAmB,EAAEC,WAAW,QAAQ,yBAAyB;AAC1E,SAASC,mBAAmB,QAAQ,qBAAqB;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,gBAAgB,QAAQ,2BAA2B;AAC5D,SACEC,kBAAkB,EAClBC,WAAW,EACXC,eAAe,EACfC,eAAe,EACfC,cAAc,EACdC,cAAc,QACT,wBAAwB;AAC/B,SAASC,aAAa,QAAQ,uBAAuB;AACrD,SACEC,oBAAoB,EACpBC,kBAAkB,EAClBC,oBAAoB,QACf,wBAAwB;AAC/B,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,kBAAkB,QAAQ,mBAAmB;AAItD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,SAAwB,EAAE;EACtD,MAAMC,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NextResponse","isSameOriginRequest","requireAuth","resolveContentModel","normalizeLang","handleCreatePage","handleFragmentList","handleLinks","handleMediaItem","handleMediaList","handleNodeItem","handleNodeList","handlePublish","handleSchema","handleDeleteTemplate","handleSaveTemplate","handleUpdateTemplate","handleUpload","isValidTypeSegment","createPuckApi","rawConfig","config","model","contentModel","handle","request","context","segments","params","puck","resource","second","third","method","length","error","console","json","status","message","unauthorized","searchParams","nextUrl","lang","get","typedResources","Set","has","join","GET","POST","PATCH","DELETE"],"sources":["../../../../src/puck-editor/internal/api/create-puck-api.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\n\nimport { isSameOriginRequest, requireAuth } from '../../../auth/server.ts';\nimport { resolveContentModel } from '../content-model.ts';\nimport { normalizeLang } from '../locale.ts';\nimport type { PuckApiConfig, PuckApiRuntime } from './config.ts';\nimport { handleCreatePage } from './handlers/create-page.ts';\nimport {\n handleFragmentList,\n handleLinks,\n handleMediaItem,\n handleMediaList,\n handleNodeItem,\n handleNodeList,\n} from './handlers/entities.ts';\nimport { handlePublish } from './handlers/publish.ts';\nimport { handleSchema } from './handlers/schema.ts';\nimport {\n handleDeleteTemplate,\n handleSaveTemplate,\n handleUpdateTemplate,\n} from './handlers/template.ts';\nimport { handleUpload } from './handlers/upload.ts';\nimport { isValidTypeSegment } from './type-segment.ts';\n\ntype PuckRouteContext = { params: Promise<{ puck?: string[] }> };\n\n/**\n * Handler factory for the Puck editor backend, mounted once as a catch-all\n * route (Auth.js pattern):\n *\n * // src/app/api/puck/[...puck]/route.ts\n * export const { GET, POST, PATCH, DELETE } = createPuckApi({ ... });\n *\n * Projects extend via Next.js routing precedence, not via config: a sibling\n * route file next to the mount adds an endpoint, a file on the same path as a\n * built-in handler shadows it.\n */\nexport function createPuckApi(rawConfig: PuckApiConfig) {\n const config: PuckApiRuntime = {\n ...rawConfig,\n model: resolveContentModel(rawConfig.contentModel),\n };\n const handle = async (request: NextRequest, context: PuckRouteContext) => {\n const segments = (await context.params).puck ?? [];\n const [resource, second, third] = segments;\n\n if (\n request.method === 'GET' &&\n resource === 'schema' &&\n segments.length === 1\n ) {\n try {\n return handleSchema(config);\n } catch (error) {\n console.error('puck api GET /schema:', error);\n return NextResponse.json(\n { status: 'error', message: 'An unexpected error occurred' },\n { status: 500 }\n );\n }\n }\n\n const unauthorized = await requireAuth();\n if (unauthorized) return unauthorized;\n\n if (request.method !== 'GET' && !isSameOriginRequest(request)) {\n return NextResponse.json(\n { status: 'error', message: 'cross-site request rejected' },\n { status: 403 }\n );\n }\n const { searchParams } = request.nextUrl;\n const lang = normalizeLang(searchParams.get('lang'));\n\n const typedResources = new Set(['node', 'media', 'fragment']);\n if (typedResources.has(resource) && !isValidTypeSegment(second)) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n }\n\n try {\n switch (request.method) {\n case 'GET':\n if (resource === 'links' && segments.length === 1) {\n return await handleLinks(config, lang);\n }\n if (resource === 'node' && segments.length === 2) {\n return await handleNodeList(config, second, searchParams);\n }\n if (resource === 'node' && segments.length === 3) {\n return await handleNodeItem(config, second, third, lang);\n }\n if (resource === 'media' && segments.length === 2) {\n return await handleMediaList(config, second, searchParams);\n }\n if (resource === 'media' && segments.length === 3) {\n return await handleMediaItem(config, second, third, lang);\n }\n if (resource === 'fragment' && segments.length === 2) {\n return await handleFragmentList(config, second, searchParams);\n }\n break;\n case 'POST':\n if (resource === 'create' && segments.length === 1) {\n return await handleCreatePage(config, request);\n }\n if (resource === 'upload' && segments.length === 1) {\n return await handleUpload(config, request);\n }\n if (resource === 'template' && segments.length === 1) {\n return await handleSaveTemplate(config, request);\n }\n break;\n case 'PATCH':\n if (resource === 'publish' && segments.length === 1) {\n return await handlePublish(config, request);\n }\n if (resource === 'template' && segments.length === 3) {\n return await handleUpdateTemplate(config, second, third, request);\n }\n break;\n case 'DELETE':\n if (resource === 'template' && segments.length === 3) {\n return await handleDeleteTemplate(config, second, third);\n }\n break;\n }\n } catch (error) {\n console.error(\n `puck api ${request.method} /${segments.join('/')}:`,\n error\n );\n return NextResponse.json(\n { status: 'error', message: 'An unexpected error occurred' },\n { status: 500 }\n );\n }\n\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n };\n\n return { GET: handle, POST: handle, PATCH: handle, DELETE: handle };\n}\n"],"mappings":"AAAA,SAAsBA,YAAY,QAAQ,aAAa;AAEvD,SAASC,mBAAmB,EAAEC,WAAW,QAAQ,yBAAyB;AAC1E,SAASC,mBAAmB,QAAQ,qBAAqB;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,gBAAgB,QAAQ,2BAA2B;AAC5D,SACEC,kBAAkB,EAClBC,WAAW,EACXC,eAAe,EACfC,eAAe,EACfC,cAAc,EACdC,cAAc,QACT,wBAAwB;AAC/B,SAASC,aAAa,QAAQ,uBAAuB;AACrD,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SACEC,oBAAoB,EACpBC,kBAAkB,EAClBC,oBAAoB,QACf,wBAAwB;AAC/B,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,kBAAkB,QAAQ,mBAAmB;AAItD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,SAAwB,EAAE;EACtD,MAAMC,MAAsB,GAAG;IAC7B,GAAGD,SAAS;IACZE,KAAK,EAAEnB,mBAAmB,CAACiB,SAAS,CAACG,YAAY;EACnD,CAAC;EACD,MAAMC,MAAM,GAAG,MAAAA,CAAOC,OAAoB,EAAEC,OAAyB,KAAK;IACxE,MAAMC,QAAQ,GAAG,CAAC,MAAMD,OAAO,CAACE,MAAM,EAAEC,IAAI,IAAI,EAAE;IAClD,MAAM,CAACC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,CAAC,GAAGL,QAAQ;IAE1C,IACEF,OAAO,CAACQ,MAAM,KAAK,KAAK,IACxBH,QAAQ,KAAK,QAAQ,IACrBH,QAAQ,CAACO,MAAM,KAAK,CAAC,EACrB;MACA,IAAI;QACF,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declare function handleSchema(config: PuckApiRuntime): NextResponse<{
4
+ status: string;
5
+ message: string;
6
+ }> | NextResponse<import("../../schema.js").PuckSchema>;
@@ -0,0 +1,41 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { generatePuckSchema } from "../../schema.js";
3
+ export function handleSchema(config) {
4
+ const puckConfigs = config.puckConfigs ?? {};
5
+ if (Object.keys(puckConfigs).length === 0) {
6
+ return NextResponse.json({
7
+ status: 'error',
8
+ message: 'Schema export is not configured. Pass puckConfigs ({ [bundleType]: puckConfig }) to createPuckApi.'
9
+ }, {
10
+ status: 501
11
+ });
12
+ }
13
+ const inputs = [];
14
+ const configWarnings = [];
15
+ for (const bundle of config.model.bundles) {
16
+ const puckConfig = puckConfigs[bundle.type];
17
+ if (!puckConfig) {
18
+ configWarnings.push(`${bundle.type}: no Puck config passed to createPuckApi, bundle missing from schema`);
19
+ continue;
20
+ }
21
+ inputs.push({
22
+ type: bundle.type,
23
+ dataField: bundle.dataField,
24
+ config: puckConfig
25
+ });
26
+ }
27
+ const bundleTypes = new Set(config.model.bundles.map(b => b.type));
28
+ for (const key of Object.keys(puckConfigs)) {
29
+ if (!bundleTypes.has(key)) {
30
+ configWarnings.push(`${key}: puckConfigs key matches no contentModel bundle, config ignored`);
31
+ }
32
+ }
33
+ const schema = generatePuckSchema(inputs);
34
+ schema.warnings.push(...configWarnings);
35
+ return NextResponse.json(schema, {
36
+ headers: {
37
+ 'Cache-Control': 'public, max-age=300'
38
+ }
39
+ });
40
+ }
41
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","names":["NextResponse","generatePuckSchema","handleSchema","config","puckConfigs","Object","keys","length","json","status","message","inputs","configWarnings","bundle","model","bundles","puckConfig","type","push","dataField","bundleTypes","Set","map","b","key","has","schema","warnings","headers"],"sources":["../../../../../src/puck-editor/internal/api/handlers/schema.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\n\nimport { generatePuckSchema } from '../../schema.ts';\nimport type { PuckApiRuntime } from '../config.ts';\n\nexport function handleSchema(config: PuckApiRuntime) {\n const puckConfigs = config.puckConfigs ?? {};\n if (Object.keys(puckConfigs).length === 0) {\n return NextResponse.json(\n {\n status: 'error',\n message:\n 'Schema export is not configured. Pass puckConfigs ({ [bundleType]: puckConfig }) to createPuckApi.',\n },\n { status: 501 }\n );\n }\n const inputs = [];\n const configWarnings: string[] = [];\n for (const bundle of config.model.bundles) {\n const puckConfig = puckConfigs[bundle.type];\n if (!puckConfig) {\n configWarnings.push(\n `${bundle.type}: no Puck config passed to createPuckApi, bundle missing from schema`\n );\n continue;\n }\n inputs.push({\n type: bundle.type,\n dataField: bundle.dataField,\n config: puckConfig,\n });\n }\n const bundleTypes = new Set(config.model.bundles.map((b) => b.type));\n for (const key of Object.keys(puckConfigs)) {\n if (!bundleTypes.has(key)) {\n configWarnings.push(\n `${key}: puckConfigs key matches no contentModel bundle, config ignored`\n );\n }\n }\n const schema = generatePuckSchema(inputs);\n schema.warnings.push(...configWarnings);\n return NextResponse.json(schema, {\n headers: { 'Cache-Control': 'public, max-age=300' },\n });\n}\n"],"mappings":"AAAA,SAASA,YAAY,QAAQ,aAAa;AAE1C,SAASC,kBAAkB,QAAQ,iBAAiB;AAGpD,OAAO,SAASC,YAAYA,CAACC,MAAsB,EAAE;EACnD,MAAMC,WAAW,GAAGD,MAAM,CAACC,WAAW,IAAI,CAAC,CAAC;EAC5C,IAAIC,MAAM,CAACC,IAAI,CAACF,WAAW,CAAC,CAACG,MAAM,KAAK,CAAC,EAAE;IACzC,OAAOP,YAAY,CAACQ,IAAI,CACtB;MACEC,MAAM,EAAE,OAAO;MACfC,OAAO,EACL;IACJ,CAAC,EACD;MAAED,MAAM,EAAE;IAAI,CAChB,CAAC;EACH;EACA,MAAME,MAAM,GAAG,EAAE;EACjB,MAAMC,cAAwB,GAAG,EAAE;EACnC,KAAK,MAAMC,MAAM,IAAIV,MAAM,CAACW,KAAK,CAACC,OAAO,EAAE;IACzC,MAAMC,UAAU,GAAGZ,WAAW,CAACS,MAAM,CAACI,IAAI,CAAC;IAC3C,IAAI,CAACD,UAAU,EAAE;MACfJ,cAAc,CAACM,IAAI,CACjB,GAAGL,MAAM,CAACI,IAAI,sEAChB,CAAC;MACD;IACF;IACAN,MAAM,CAACO,IAAI,CAAC;MACVD,IAAI,EAAEJ,MAAM,CAACI,IAAI;MACjBE,SAAS,EAAEN,MAAM,CAACM,SAAS;MAC3BhB,MAAM,EAAEa;IACV,CAAC,CAAC;EACJ;EACA,MAAMI,WAAW,GAAG,IAAIC,GAAG,CAAClB,MAAM,CAACW,KAAK,CAACC,OAAO,CAACO,GAAG,CAAEC,CAAC,IAAKA,CAAC,CAACN,IAAI,CAAC,CAAC;EACpE,KAAK,MAAMO,GAAG,IAAInB,MAAM,CAACC,IAAI,CAACF,WAAW,CAAC,EAAE;IAC1C,IAAI,CAACgB,WAAW,CAACK,GAAG,CAACD,GAAG,CAAC,EAAE;MACzBZ,cAAc,CAACM,IAAI,CACjB,GAAGM,GAAG,kEACR,CAAC;IACH;EACF;EACA,MAAME,MAAM,GAAGzB,kBAAkB,CAACU,MAAM,CAAC;EACzCe,MAAM,CAACC,QAAQ,CAACT,IAAI,CAAC,GAAGN,cAAc,CAAC;EACvC,OAAOZ,YAAY,CAACQ,IAAI,CAACkB,MAAM,EAAE;IAC/BE,OAAO,EAAE;MAAE,eAAe,EAAE;IAAsB;EACpD,CAAC,CAAC;AACJ","ignoreList":[]}
@@ -9,6 +9,11 @@ export interface CheckboxGroupFieldOptions {
9
9
  export declare const createCheckboxGroupField: ({ label, options, helperText, }: CheckboxGroupFieldOptions) => {
10
10
  type: "custom";
11
11
  label: string | undefined;
12
+ metadata: {
13
+ nodehive: {
14
+ kind: string;
15
+ };
16
+ };
12
17
  render: ({ field, value, onChange }: {
13
18
  field: import("@puckeditor/core").CustomField<string[]>;
14
19
  name: string;
@@ -8,6 +8,11 @@ export const createCheckboxGroupField = ({
8
8
  return {
9
9
  type: 'custom',
10
10
  label,
11
+ metadata: {
12
+ nodehive: {
13
+ kind: 'value'
14
+ }
15
+ },
11
16
  render: ({
12
17
  field,
13
18
  value,
@@ -1 +1 @@
1
- {"version":3,"file":"create-checkbox-group-field.js","names":["CheckboxGroupField","jsx","_jsx","createCheckboxGroupField","label","options","helperText","type","render","field","value","onChange"],"sources":["../../../../../src/puck-editor/internal/fields/checkbox-group/create-checkbox-group-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport { CheckboxGroupField } from './checkbox-group-field.tsx';\n\nexport interface CheckboxGroupFieldOptions {\n label?: string;\n options: Array<{ label: string; value: string }>;\n helperText?: string;\n}\n\nexport const createCheckboxGroupField = ({\n label,\n options,\n helperText,\n}: CheckboxGroupFieldOptions) => {\n return {\n type: 'custom' as const,\n label,\n render: (({ field, value, onChange }) => (\n <CheckboxGroupField\n label={field.label ?? label}\n options={options}\n value={value}\n onChange={onChange}\n helperText={helperText}\n />\n )) satisfies CustomFieldRender<string[]>,\n };\n};\n"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,2BAA4B;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAQhE,OAAO,MAAMC,wBAAwB,GAAGA,CAAC;EACvCC,KAAK;EACLC,OAAO;EACPC;AACyB,CAAC,KAAK;EAC/B,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC;IAAS,CAAC,kBAClCT,IAAA,CAACF,kBAAkB;MACjBI,KAAK,EAAEK,KAAK,CAACL,KAAK,IAAIA,KAAM;MAC5BC,OAAO,EAAEA,OAAQ;MACjBK,KAAK,EAAEA,KAAM;MACbC,QAAQ,EAAEA,QAAS;MACnBL,UAAU,EAAEA;IAAW,CACxB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-checkbox-group-field.js","names":["CheckboxGroupField","jsx","_jsx","createCheckboxGroupField","label","options","helperText","type","metadata","nodehive","kind","render","field","value","onChange"],"sources":["../../../../../src/puck-editor/internal/fields/checkbox-group/create-checkbox-group-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { PuckSchemaPropKind } from '../../schema.ts';\nimport { CheckboxGroupField } from './checkbox-group-field.tsx';\n\nexport interface CheckboxGroupFieldOptions {\n label?: string;\n options: Array<{ label: string; value: string }>;\n helperText?: string;\n}\n\nexport const createCheckboxGroupField = ({\n label,\n options,\n helperText,\n}: CheckboxGroupFieldOptions) => {\n return {\n type: 'custom' as const,\n label,\n metadata: { nodehive: { kind: 'value' satisfies PuckSchemaPropKind } },\n render: (({ field, value, onChange }) => (\n <CheckboxGroupField\n label={field.label ?? label}\n options={options}\n value={value}\n onChange={onChange}\n helperText={helperText}\n />\n )) satisfies CustomFieldRender<string[]>,\n };\n};\n"],"mappings":"AAGA,SAASA,kBAAkB,QAAQ,2BAA4B;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAQhE,OAAO,MAAMC,wBAAwB,GAAGA,CAAC;EACvCC,KAAK;EACLC,OAAO;EACPC;AACyB,CAAC,KAAK;EAC/B,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,QAAQ,EAAE;MAAEC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAqC;IAAE,CAAC;IACtEC,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC;IAAS,CAAC,kBAClCZ,IAAA,CAACF,kBAAkB;MACjBI,KAAK,EAAEQ,KAAK,CAACR,KAAK,IAAIA,KAAM;MAC5BC,OAAO,EAAEA,OAAQ;MACjBQ,KAAK,EAAEA,KAAM;MACbC,QAAQ,EAAEA,QAAS;MACnBR,UAAU,EAAEA;IAAW,CACxB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
@@ -4,6 +4,11 @@ export interface DatePickerFieldOptions {
4
4
  export declare const createDatePickerField: ({ label, }?: DatePickerFieldOptions) => {
5
5
  type: "custom";
6
6
  label: string | undefined;
7
+ metadata: {
8
+ nodehive: {
9
+ kind: string;
10
+ };
11
+ };
7
12
  render: ({ field, value, onChange }: {
8
13
  field: import("@puckeditor/core").CustomField<string>;
9
14
  name: string;
@@ -6,6 +6,11 @@ export const createDatePickerField = ({
6
6
  return {
7
7
  type: 'custom',
8
8
  label,
9
+ metadata: {
10
+ nodehive: {
11
+ kind: 'value'
12
+ }
13
+ },
9
14
  render: ({
10
15
  field,
11
16
  value,
@@ -1 +1 @@
1
- {"version":3,"file":"create-date-picker-field.js","names":["DatePicker","jsx","_jsx","createDatePickerField","label","type","render","field","value","onChange","date"],"sources":["../../../../../src/puck-editor/internal/fields/date-picker/create-date-picker-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport { DatePicker } from './date-picker.tsx';\n\nexport interface DatePickerFieldOptions {\n label?: string;\n}\n\nexport const createDatePickerField = ({\n label,\n}: DatePickerFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n render: (({ field, value, onChange }) => (\n <DatePicker\n date={value}\n onChange={onChange}\n label={field.label ?? label}\n />\n )) satisfies CustomFieldRender<string>,\n };\n};\n"],"mappings":"AAEA,SAASA,UAAU,QAAQ,kBAAmB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAM/C,OAAO,MAAMC,qBAAqB,GAAGA,CAAC;EACpCC;AACsB,CAAC,GAAG,CAAC,CAAC,KAAK;EACjC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBD,KAAK;IACLE,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC;IAAS,CAAC,kBAClCP,IAAA,CAACF,UAAU;MACTU,IAAI,EAAEF,KAAM;MACZC,QAAQ,EAAEA,QAAS;MACnBL,KAAK,EAAEG,KAAK,CAACH,KAAK,IAAIA;IAAM,CAC7B;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-date-picker-field.js","names":["DatePicker","jsx","_jsx","createDatePickerField","label","type","metadata","nodehive","kind","render","field","value","onChange","date"],"sources":["../../../../../src/puck-editor/internal/fields/date-picker/create-date-picker-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { PuckSchemaPropKind } from '../../schema.ts';\nimport { DatePicker } from './date-picker.tsx';\n\nexport interface DatePickerFieldOptions {\n label?: string;\n}\n\nexport const createDatePickerField = ({\n label,\n}: DatePickerFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: { nodehive: { kind: 'value' satisfies PuckSchemaPropKind } },\n render: (({ field, value, onChange }) => (\n <DatePicker\n date={value}\n onChange={onChange}\n label={field.label ?? label}\n />\n )) satisfies CustomFieldRender<string>,\n };\n};\n"],"mappings":"AAGA,SAASA,UAAU,QAAQ,kBAAmB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAM/C,OAAO,MAAMC,qBAAqB,GAAGA,CAAC;EACpCC;AACsB,CAAC,GAAG,CAAC,CAAC,KAAK;EACjC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBD,KAAK;IACLE,QAAQ,EAAE;MAAEC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAqC;IAAE,CAAC;IACtEC,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC;IAAS,CAAC,kBAClCV,IAAA,CAACF,UAAU;MACTa,IAAI,EAAEF,KAAM;MACZC,QAAQ,EAAEA,QAAS;MACnBR,KAAK,EAAEM,KAAK,CAACN,KAAK,IAAIA;IAAM,CAC7B;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
@@ -11,6 +11,11 @@ interface LinkFieldOptions {
11
11
  export declare const createLinkField: ({ label }?: LinkFieldOptions) => {
12
12
  type: "custom";
13
13
  label: string | undefined;
14
+ metadata: {
15
+ nodehive: {
16
+ kind: string;
17
+ };
18
+ };
14
19
  render: ({ field, value, onChange, id }: {
15
20
  field: import("@puckeditor/core").CustomField<string | LinkValue>;
16
21
  name: string;
@@ -12,6 +12,11 @@ export const createLinkField = ({
12
12
  return {
13
13
  type: 'custom',
14
14
  label,
15
+ metadata: {
16
+ nodehive: {
17
+ kind: 'link'
18
+ }
19
+ },
15
20
  // Key by the field id so switching between components (or array items)
16
21
  // remounts the picker — its mode/anchor state is derived from the initial
17
22
  // href, so reusing the same instance would show a stale mode for the new
@@ -1 +1 @@
1
- {"version":3,"file":"create-link-field.js","names":["LinkPickerField","jsx","_jsx","createLinkField","label","type","render","field","value","onChange","id"],"sources":["../../../../../src/puck-editor/internal/fields/link-picker/create-link-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport LinkPickerField from './link-picker-field.tsx';\nimport { type LinkValue } from './link-value.ts';\n\ninterface LinkFieldOptions {\n label?: string;\n}\n\n/**\n * Reusable LinkPicker field. Stores a bundled {@link LinkValue}\n * (`{ href, target }`) and supports internal pages, external URLs, in-page\n * anchors and a target override. Consume the stored value with `resolveLink()`\n * from `@nodehive/nextjs/puck-editor/fields` in the component's `render`.\n */\nexport const createLinkField = ({ label }: LinkFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n // Key by the field id so switching between components (or array items)\n // remounts the picker — its mode/anchor state is derived from the initial\n // href, so reusing the same instance would show a stale mode for the new\n // value.\n render: (({ field, value, onChange, id }) => (\n <LinkPickerField\n key={id}\n label={field.label ?? label}\n value={value}\n onChange={onChange}\n />\n )) satisfies CustomFieldRender<LinkValue | string>,\n };\n};\n"],"mappings":"AAEA,OAAOA,eAAe,MAAM,wBAAyB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAOtD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,eAAe,GAAGA,CAAC;EAAEC;AAAwB,CAAC,GAAG,CAAC,CAAC,KAAK;EACnE,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBD,KAAK;IACL;IACA;IACA;IACA;IACAE,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC,QAAQ;MAAEC;IAAG,CAAC,kBACtCR,IAAA,CAACF,eAAe;MAEdI,KAAK,EAAEG,KAAK,CAACH,KAAK,IAAIA,KAAM;MAC5BI,KAAK,EAAEA,KAAM;MACbC,QAAQ,EAAEA;IAAS,GAHdC,EAIN;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-link-field.js","names":["LinkPickerField","jsx","_jsx","createLinkField","label","type","metadata","nodehive","kind","render","field","value","onChange","id"],"sources":["../../../../../src/puck-editor/internal/fields/link-picker/create-link-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { PuckSchemaPropKind } from '../../schema.ts';\nimport LinkPickerField from './link-picker-field.tsx';\nimport { type LinkValue } from './link-value.ts';\n\ninterface LinkFieldOptions {\n label?: string;\n}\n\n/**\n * Reusable LinkPicker field. Stores a bundled {@link LinkValue}\n * (`{ href, target }`) and supports internal pages, external URLs, in-page\n * anchors and a target override. Consume the stored value with `resolveLink()`\n * from `@nodehive/nextjs/puck-editor/fields` in the component's `render`.\n */\nexport const createLinkField = ({ label }: LinkFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: { nodehive: { kind: 'link' satisfies PuckSchemaPropKind } },\n // Key by the field id so switching between components (or array items)\n // remounts the picker — its mode/anchor state is derived from the initial\n // href, so reusing the same instance would show a stale mode for the new\n // value.\n render: (({ field, value, onChange, id }) => (\n <LinkPickerField\n key={id}\n label={field.label ?? label}\n value={value}\n onChange={onChange}\n />\n )) satisfies CustomFieldRender<LinkValue | string>,\n };\n};\n"],"mappings":"AAGA,OAAOA,eAAe,MAAM,wBAAyB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAOtD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,eAAe,GAAGA,CAAC;EAAEC;AAAwB,CAAC,GAAG,CAAC,CAAC,KAAK;EACnE,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBD,KAAK;IACLE,QAAQ,EAAE;MAAEC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAoC;IAAE,CAAC;IACrE;IACA;IACA;IACA;IACAC,MAAM,EAAGA,CAAC;MAAEC,KAAK;MAAEC,KAAK;MAAEC,QAAQ;MAAEC;IAAG,CAAC,kBACtCX,IAAA,CAACF,eAAe;MAEdI,KAAK,EAAEM,KAAK,CAACN,KAAK,IAAIA,KAAM;MAC5BO,KAAK,EAAEA,KAAM;MACbC,QAAQ,EAAEA;IAAS,GAHdC,EAIN;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
@@ -10,6 +10,9 @@ export declare const createMediaArrayField: ({ mediaTypes, label, fields, crop,
10
10
  type: "custom";
11
11
  label: string | undefined;
12
12
  metadata: {
13
+ nodehive: {
14
+ kind: string;
15
+ };
13
16
  ai: {
14
17
  bind: string;
15
18
  instructions: string;
@@ -10,6 +10,9 @@ export const createMediaArrayField = ({
10
10
  type: 'custom',
11
11
  label,
12
12
  metadata: {
13
+ nodehive: {
14
+ kind: 'media'
15
+ },
13
16
  ai: {
14
17
  bind: 'search_media',
15
18
  instructions: `Value must be an array of full media objects returned by search_media (type: ${mediaTypes.join(', ')}). Never construct entries by hand.`
@@ -1 +1 @@
1
- {"version":3,"file":"create-media-array-field.js","names":["MediaArrayField","jsx","_jsx","createMediaArrayField","mediaTypes","label","fields","crop","type","metadata","ai","bind","instructions","join","render","onChange","value","field","cropConfig"],"sources":["../../../../../src/puck-editor/internal/fields/media-array/create-media-array-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { MediaCropConfig } from '../media-selector/crop-types.ts';\nimport { MediaItem } from '../media-selector/media-selector-field.tsx';\nimport { MediaArrayField } from './media-array-field.tsx';\n\nexport interface MediaArrayFieldOptions {\n mediaTypes?: string[];\n label?: string;\n fields?: string[]; // Array of property paths to save from API response\n crop?: MediaCropConfig;\n}\n\nexport const createMediaArrayField = ({\n mediaTypes = ['image'],\n label,\n fields,\n crop,\n}: MediaArrayFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: {\n ai: {\n bind: 'search_media',\n instructions: `Value must be an array of full media objects returned by search_media (type: ${mediaTypes.join(', ')}). Never construct entries by hand.`,\n },\n },\n render: (({ onChange, value, field }) => (\n <MediaArrayField\n onChange={onChange}\n value={value}\n mediaTypes={mediaTypes}\n label={field.label ?? label}\n fields={fields}\n cropConfig={crop}\n />\n )) satisfies CustomFieldRender<MediaItem[] | null>,\n };\n};\n"],"mappings":"AAIA,SAASA,eAAe,QAAQ,wBAAyB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAS1D,OAAO,MAAMC,qBAAqB,GAAGA,CAAC;EACpCC,UAAU,GAAG,CAAC,OAAO,CAAC;EACtBC,KAAK;EACLC,MAAM;EACNC;AACsB,CAAC,GAAG,CAAC,CAAC,KAAK;EACjC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,QAAQ,EAAE;MACRC,EAAE,EAAE;QACFC,IAAI,EAAE,cAAc;QACpBC,YAAY,EAAE,gFAAgFR,UAAU,CAACS,IAAI,CAAC,IAAI,CAAC;MACrH;IACF,CAAC;IACDC,MAAM,EAAGA,CAAC;MAAEC,QAAQ;MAAEC,KAAK;MAAEC;IAAM,CAAC,kBAClCf,IAAA,CAACF,eAAe;MACde,QAAQ,EAAEA,QAAS;MACnBC,KAAK,EAAEA,KAAM;MACbZ,UAAU,EAAEA,UAAW;MACvBC,KAAK,EAAEY,KAAK,CAACZ,KAAK,IAAIA,KAAM;MAC5BC,MAAM,EAAEA,MAAO;MACfY,UAAU,EAAEX;IAAK,CAClB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-media-array-field.js","names":["MediaArrayField","jsx","_jsx","createMediaArrayField","mediaTypes","label","fields","crop","type","metadata","nodehive","kind","ai","bind","instructions","join","render","onChange","value","field","cropConfig"],"sources":["../../../../../src/puck-editor/internal/fields/media-array/create-media-array-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { PuckSchemaPropKind } from '../../schema.ts';\nimport type { MediaCropConfig } from '../media-selector/crop-types.ts';\nimport { MediaItem } from '../media-selector/media-selector-field.tsx';\nimport { MediaArrayField } from './media-array-field.tsx';\n\nexport interface MediaArrayFieldOptions {\n mediaTypes?: string[];\n label?: string;\n fields?: string[]; // Array of property paths to save from API response\n crop?: MediaCropConfig;\n}\n\nexport const createMediaArrayField = ({\n mediaTypes = ['image'],\n label,\n fields,\n crop,\n}: MediaArrayFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: {\n nodehive: { kind: 'media' satisfies PuckSchemaPropKind },\n ai: {\n bind: 'search_media',\n instructions: `Value must be an array of full media objects returned by search_media (type: ${mediaTypes.join(', ')}). Never construct entries by hand.`,\n },\n },\n render: (({ onChange, value, field }) => (\n <MediaArrayField\n onChange={onChange}\n value={value}\n mediaTypes={mediaTypes}\n label={field.label ?? label}\n fields={fields}\n cropConfig={crop}\n />\n )) satisfies CustomFieldRender<MediaItem[] | null>,\n };\n};\n"],"mappings":"AAKA,SAASA,eAAe,QAAQ,wBAAyB;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAS1D,OAAO,MAAMC,qBAAqB,GAAGA,CAAC;EACpCC,UAAU,GAAG,CAAC,OAAO,CAAC;EACtBC,KAAK;EACLC,MAAM;EACNC;AACsB,CAAC,GAAG,CAAC,CAAC,KAAK;EACjC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,QAAQ,EAAE;MACRC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAqC,CAAC;MACxDC,EAAE,EAAE;QACFC,IAAI,EAAE,cAAc;QACpBC,YAAY,EAAE,gFAAgFV,UAAU,CAACW,IAAI,CAAC,IAAI,CAAC;MACrH;IACF,CAAC;IACDC,MAAM,EAAGA,CAAC;MAAEC,QAAQ;MAAEC,KAAK;MAAEC;IAAM,CAAC,kBAClCjB,IAAA,CAACF,eAAe;MACdiB,QAAQ,EAAEA,QAAS;MACnBC,KAAK,EAAEA,KAAM;MACbd,UAAU,EAAEA,UAAW;MACvBC,KAAK,EAAEc,KAAK,CAACd,KAAK,IAAIA,KAAM;MAC5BC,MAAM,EAAEA,MAAO;MACfc,UAAU,EAAEb;IAAK,CAClB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
@@ -10,6 +10,9 @@ export declare const createMediaSelectorField: ({ mediaTypes, label, fields, cro
10
10
  type: "custom";
11
11
  label: string | undefined;
12
12
  metadata: {
13
+ nodehive: {
14
+ kind: string;
15
+ };
13
16
  ai: {
14
17
  bind: string;
15
18
  instructions: string;
@@ -10,6 +10,9 @@ export const createMediaSelectorField = ({
10
10
  type: 'custom',
11
11
  label,
12
12
  metadata: {
13
+ nodehive: {
14
+ kind: 'media'
15
+ },
13
16
  ai: {
14
17
  bind: 'search_media',
15
18
  instructions: `Value must be a full media object returned by search_media (type: ${mediaTypes.join(', ')}). Never construct one by hand.`
@@ -1 +1 @@
1
- {"version":3,"file":"create-media-selector-field.js","names":["MediaSelectorField","jsx","_jsx","createMediaSelectorField","mediaTypes","label","fields","crop","type","metadata","ai","bind","instructions","join","render","onChange","value","field","cropConfig"],"sources":["../../../../../src/puck-editor/internal/fields/media-selector/create-media-selector-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { MediaCropConfig } from './crop-types.ts';\nimport { MediaItem, MediaSelectorField } from './media-selector-field.tsx';\n\nexport interface MediaSelectorFieldOptions {\n mediaTypes?: string[];\n label?: string;\n fields?: string[]; // Array of property paths to save from API response\n crop?: MediaCropConfig;\n}\n\nexport const createMediaSelectorField = ({\n mediaTypes = ['image'],\n label,\n fields,\n crop,\n}: MediaSelectorFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: {\n ai: {\n bind: 'search_media',\n instructions: `Value must be a full media object returned by search_media (type: ${mediaTypes.join(', ')}). Never construct one by hand.`,\n },\n },\n render: (({ onChange, value, field }) => (\n <MediaSelectorField\n onChange={onChange}\n value={value}\n mediaTypes={mediaTypes}\n label={field.label ?? label}\n fields={fields}\n cropConfig={crop}\n />\n )) satisfies CustomFieldRender<MediaItem | null>,\n };\n};\n"],"mappings":"AAGA,SAAoBA,kBAAkB,QAAQ,2BAA4B;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAS3E,OAAO,MAAMC,wBAAwB,GAAGA,CAAC;EACvCC,UAAU,GAAG,CAAC,OAAO,CAAC;EACtBC,KAAK;EACLC,MAAM;EACNC;AACyB,CAAC,GAAG,CAAC,CAAC,KAAK;EACpC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,QAAQ,EAAE;MACRC,EAAE,EAAE;QACFC,IAAI,EAAE,cAAc;QACpBC,YAAY,EAAE,qEAAqER,UAAU,CAACS,IAAI,CAAC,IAAI,CAAC;MAC1G;IACF,CAAC;IACDC,MAAM,EAAGA,CAAC;MAAEC,QAAQ;MAAEC,KAAK;MAAEC;IAAM,CAAC,kBAClCf,IAAA,CAACF,kBAAkB;MACjBe,QAAQ,EAAEA,QAAS;MACnBC,KAAK,EAAEA,KAAM;MACbZ,UAAU,EAAEA,UAAW;MACvBC,KAAK,EAAEY,KAAK,CAACZ,KAAK,IAAIA,KAAM;MAC5BC,MAAM,EAAEA,MAAO;MACfY,UAAU,EAAEX;IAAK,CAClB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-media-selector-field.js","names":["MediaSelectorField","jsx","_jsx","createMediaSelectorField","mediaTypes","label","fields","crop","type","metadata","nodehive","kind","ai","bind","instructions","join","render","onChange","value","field","cropConfig"],"sources":["../../../../../src/puck-editor/internal/fields/media-selector/create-media-selector-field.tsx"],"sourcesContent":["import type { CustomFieldRender } from '@puckeditor/core';\n\nimport type { PuckSchemaPropKind } from '../../schema.ts';\nimport type { MediaCropConfig } from './crop-types.ts';\nimport { MediaItem, MediaSelectorField } from './media-selector-field.tsx';\n\nexport interface MediaSelectorFieldOptions {\n mediaTypes?: string[];\n label?: string;\n fields?: string[]; // Array of property paths to save from API response\n crop?: MediaCropConfig;\n}\n\nexport const createMediaSelectorField = ({\n mediaTypes = ['image'],\n label,\n fields,\n crop,\n}: MediaSelectorFieldOptions = {}) => {\n return {\n type: 'custom' as const,\n label,\n metadata: {\n nodehive: { kind: 'media' satisfies PuckSchemaPropKind },\n ai: {\n bind: 'search_media',\n instructions: `Value must be a full media object returned by search_media (type: ${mediaTypes.join(', ')}). Never construct one by hand.`,\n },\n },\n render: (({ onChange, value, field }) => (\n <MediaSelectorField\n onChange={onChange}\n value={value}\n mediaTypes={mediaTypes}\n label={field.label ?? label}\n fields={fields}\n cropConfig={crop}\n />\n )) satisfies CustomFieldRender<MediaItem | null>,\n };\n};\n"],"mappings":"AAIA,SAAoBA,kBAAkB,QAAQ,2BAA4B;AAAC,SAAAC,GAAA,IAAAC,IAAA;AAS3E,OAAO,MAAMC,wBAAwB,GAAGA,CAAC;EACvCC,UAAU,GAAG,CAAC,OAAO,CAAC;EACtBC,KAAK;EACLC,MAAM;EACNC;AACyB,CAAC,GAAG,CAAC,CAAC,KAAK;EACpC,OAAO;IACLC,IAAI,EAAE,QAAiB;IACvBH,KAAK;IACLI,QAAQ,EAAE;MACRC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAqC,CAAC;MACxDC,EAAE,EAAE;QACFC,IAAI,EAAE,cAAc;QACpBC,YAAY,EAAE,qEAAqEV,UAAU,CAACW,IAAI,CAAC,IAAI,CAAC;MAC1G;IACF,CAAC;IACDC,MAAM,EAAGA,CAAC;MAAEC,QAAQ;MAAEC,KAAK;MAAEC;IAAM,CAAC,kBAClCjB,IAAA,CAACF,kBAAkB;MACjBiB,QAAQ,EAAEA,QAAS;MACnBC,KAAK,EAAEA,KAAM;MACbd,UAAU,EAAEA,UAAW;MACvBC,KAAK,EAAEc,KAAK,CAACd,KAAK,IAAIA,KAAM;MAC5BC,MAAM,EAAEA,MAAO;MACfc,UAAU,EAAEb;IAAK,CAClB;EAEL,CAAC;AACH,CAAC","ignoreList":[]}
@@ -18,6 +18,11 @@ export interface NodeSelectorFieldOptions<TItem extends NodeSelectorItem = NodeS
18
18
  export declare const createNodeSelectorField: <TItem extends NodeSelectorItem = NodeSelectorItem>({ nodeType, label, placeholder, showSearch, initialQuery, searchFields, fields, getItemSummary, mapRow, mapProp, }: NodeSelectorFieldOptions<TItem>) => {
19
19
  type: "external";
20
20
  label: string;
21
+ metadata: {
22
+ nodehive: {
23
+ kind: string;
24
+ };
25
+ };
21
26
  placeholder: string;
22
27
  showSearch: boolean;
23
28
  initialQuery: string;
@@ -15,6 +15,11 @@ export const createNodeSelectorField = ({
15
15
  return {
16
16
  type: 'external',
17
17
  label,
18
+ metadata: {
19
+ nodehive: {
20
+ kind: 'entity'
21
+ }
22
+ },
18
23
  placeholder,
19
24
  showSearch,
20
25
  initialQuery,
@@ -1 +1 @@
1
- {"version":3,"file":"create-node-selector-field.js","names":["fetchNodeList","getPathLocale","createNodeSelectorField","nodeType","label","placeholder","showSearch","initialQuery","searchFields","fields","getItemSummary","mapRow","mapProp","type","fetchList","query","lang","window","location","pathname","item","summary","title"],"sources":["../../../../../src/puck-editor/internal/fields/node-selector/create-node-selector-field.ts"],"sourcesContent":["import { fetchNodeList } from '../../api/client.ts';\nimport { getPathLocale } from '../../locale.ts';\n\nexport type NodeSelectorItem = {\n title?: string | null;\n [key: string]: unknown;\n};\n\nexport interface NodeSelectorFieldOptions<\n TItem extends NodeSelectorItem = NodeSelectorItem,\n> {\n nodeType: string;\n label?: string;\n locale?: string;\n placeholder?: string;\n showSearch?: boolean;\n initialQuery?: string;\n searchFields?: string[];\n fields?: string[];\n getItemSummary?: (item: TItem) => string;\n mapRow?: (item: TItem) => TItem;\n mapProp?: (item: TItem) => unknown;\n}\n\nexport const createNodeSelectorField = <\n TItem extends NodeSelectorItem = NodeSelectorItem,\n>({\n nodeType,\n label = 'Node',\n placeholder = `Select ${nodeType}`,\n showSearch = true,\n initialQuery = '',\n searchFields = ['title'],\n fields,\n getItemSummary,\n mapRow,\n mapProp,\n}: NodeSelectorFieldOptions<TItem>) => {\n return {\n type: 'external' as const,\n label,\n placeholder,\n showSearch,\n initialQuery,\n fetchList: async ({ query }: { query?: string } = {}): Promise<TItem[]> =>\n fetchNodeList<TItem>(nodeType, {\n lang: getPathLocale(window.location.pathname),\n query,\n searchFields,\n fields,\n }),\n getItemSummary:\n getItemSummary ||\n ((item: TItem) => {\n const summary = item?.title;\n return typeof summary === 'string' ? summary : '';\n }),\n mapRow:\n mapRow ||\n ((item: TItem): TItem => {\n return item;\n }),\n mapProp,\n };\n};\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,qBAAqB;AACnD,SAASC,aAAa,QAAQ,iBAAiB;AAuB/C,OAAO,MAAMC,uBAAuB,GAAGA,CAErC;EACAC,QAAQ;EACRC,KAAK,GAAG,MAAM;EACdC,WAAW,GAAG,UAAUF,QAAQ,EAAE;EAClCG,UAAU,GAAG,IAAI;EACjBC,YAAY,GAAG,EAAE;EACjBC,YAAY,GAAG,CAAC,OAAO,CAAC;EACxBC,MAAM;EACNC,cAAc;EACdC,MAAM;EACNC;AAC+B,CAAC,KAAK;EACrC,OAAO;IACLC,IAAI,EAAE,UAAmB;IACzBT,KAAK;IACLC,WAAW;IACXC,UAAU;IACVC,YAAY;IACZO,SAAS,EAAE,MAAAA,CAAO;MAAEC;IAA0B,CAAC,GAAG,CAAC,CAAC,KAClDf,aAAa,CAAQG,QAAQ,EAAE;MAC7Ba,IAAI,EAAEf,aAAa,CAACgB,MAAM,CAACC,QAAQ,CAACC,QAAQ,CAAC;MAC7CJ,KAAK;MACLP,YAAY;MACZC;IACF,CAAC,CAAC;IACJC,cAAc,EACZA,cAAc,KACZU,IAAW,IAAK;MAChB,MAAMC,OAAO,GAAGD,IAAI,EAAEE,KAAK;MAC3B,OAAO,OAAOD,OAAO,KAAK,QAAQ,GAAGA,OAAO,GAAG,EAAE;IACnD,CAAC,CAAC;IACJV,MAAM,EACJA,MAAM,KACJS,IAAW,IAAY;MACvB,OAAOA,IAAI;IACb,CAAC,CAAC;IACJR;EACF,CAAC;AACH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"create-node-selector-field.js","names":["fetchNodeList","getPathLocale","createNodeSelectorField","nodeType","label","placeholder","showSearch","initialQuery","searchFields","fields","getItemSummary","mapRow","mapProp","type","metadata","nodehive","kind","fetchList","query","lang","window","location","pathname","item","summary","title"],"sources":["../../../../../src/puck-editor/internal/fields/node-selector/create-node-selector-field.ts"],"sourcesContent":["import { fetchNodeList } from '../../api/client.ts';\nimport { getPathLocale } from '../../locale.ts';\nimport type { PuckSchemaPropKind } from '../../schema.ts';\n\nexport type NodeSelectorItem = {\n title?: string | null;\n [key: string]: unknown;\n};\n\nexport interface NodeSelectorFieldOptions<\n TItem extends NodeSelectorItem = NodeSelectorItem,\n> {\n nodeType: string;\n label?: string;\n locale?: string;\n placeholder?: string;\n showSearch?: boolean;\n initialQuery?: string;\n searchFields?: string[];\n fields?: string[];\n getItemSummary?: (item: TItem) => string;\n mapRow?: (item: TItem) => TItem;\n mapProp?: (item: TItem) => unknown;\n}\n\nexport const createNodeSelectorField = <\n TItem extends NodeSelectorItem = NodeSelectorItem,\n>({\n nodeType,\n label = 'Node',\n placeholder = `Select ${nodeType}`,\n showSearch = true,\n initialQuery = '',\n searchFields = ['title'],\n fields,\n getItemSummary,\n mapRow,\n mapProp,\n}: NodeSelectorFieldOptions<TItem>) => {\n return {\n type: 'external' as const,\n label,\n metadata: { nodehive: { kind: 'entity' satisfies PuckSchemaPropKind } },\n placeholder,\n showSearch,\n initialQuery,\n fetchList: async ({ query }: { query?: string } = {}): Promise<TItem[]> =>\n fetchNodeList<TItem>(nodeType, {\n lang: getPathLocale(window.location.pathname),\n query,\n searchFields,\n fields,\n }),\n getItemSummary:\n getItemSummary ||\n ((item: TItem) => {\n const summary = item?.title;\n return typeof summary === 'string' ? summary : '';\n }),\n mapRow:\n mapRow ||\n ((item: TItem): TItem => {\n return item;\n }),\n mapProp,\n };\n};\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,qBAAqB;AACnD,SAASC,aAAa,QAAQ,iBAAiB;AAwB/C,OAAO,MAAMC,uBAAuB,GAAGA,CAErC;EACAC,QAAQ;EACRC,KAAK,GAAG,MAAM;EACdC,WAAW,GAAG,UAAUF,QAAQ,EAAE;EAClCG,UAAU,GAAG,IAAI;EACjBC,YAAY,GAAG,EAAE;EACjBC,YAAY,GAAG,CAAC,OAAO,CAAC;EACxBC,MAAM;EACNC,cAAc;EACdC,MAAM;EACNC;AAC+B,CAAC,KAAK;EACrC,OAAO;IACLC,IAAI,EAAE,UAAmB;IACzBT,KAAK;IACLU,QAAQ,EAAE;MAAEC,QAAQ,EAAE;QAAEC,IAAI,EAAE;MAAsC;IAAE,CAAC;IACvEX,WAAW;IACXC,UAAU;IACVC,YAAY;IACZU,SAAS,EAAE,MAAAA,CAAO;MAAEC;IAA0B,CAAC,GAAG,CAAC,CAAC,KAClDlB,aAAa,CAAQG,QAAQ,EAAE;MAC7BgB,IAAI,EAAElB,aAAa,CAACmB,MAAM,CAACC,QAAQ,CAACC,QAAQ,CAAC;MAC7CJ,KAAK;MACLV,YAAY;MACZC;IACF,CAAC,CAAC;IACJC,cAAc,EACZA,cAAc,KACZa,IAAW,IAAK;MAChB,MAAMC,OAAO,GAAGD,IAAI,EAAEE,KAAK;MAC3B,OAAO,OAAOD,OAAO,KAAK,QAAQ,GAAGA,OAAO,GAAG,EAAE;IACnD,CAAC,CAAC;IACJb,MAAM,EACJA,MAAM,KACJY,IAAW,IAAY;MACvB,OAAOA,IAAI;IACb,CAAC,CAAC;IACJX;EACF,CAAC;AACH,CAAC","ignoreList":[]}
@@ -0,0 +1,28 @@
1
+ import type { Config } from '@puckeditor/core';
2
+ export declare const PUCK_SCHEMA_VERSION = 1;
3
+ declare const KINDS: readonly ["text", "richtext", "slot", "array", "object", "media", "entity", "link", "value", "opaque"];
4
+ export type PuckSchemaPropKind = (typeof KINDS)[number];
5
+ export type PuckSchemaProp = {
6
+ kind: PuckSchemaPropKind;
7
+ fields?: Record<string, PuckSchemaProp>;
8
+ };
9
+ export type PuckSchemaComponent = {
10
+ props: Record<string, PuckSchemaProp>;
11
+ };
12
+ export type PuckSchemaBundle = {
13
+ dataField: string;
14
+ root: PuckSchemaComponent;
15
+ components: Record<string, PuckSchemaComponent>;
16
+ };
17
+ export type PuckSchema = {
18
+ version: number;
19
+ bundles: Record<string, PuckSchemaBundle>;
20
+ warnings: string[];
21
+ };
22
+ export type PuckSchemaBundleInput = {
23
+ type: string;
24
+ dataField: string;
25
+ config: Config;
26
+ };
27
+ export declare function generatePuckSchema(bundles: PuckSchemaBundleInput[]): PuckSchema;
28
+ export {};
@@ -0,0 +1,83 @@
1
+ export const PUCK_SCHEMA_VERSION = 1;
2
+ const KINDS = ['text', 'richtext', 'slot', 'array', 'object', 'media', 'entity', 'link', 'value', 'opaque'];
3
+ function isKind(value) {
4
+ return KINDS.includes(value);
5
+ }
6
+ const DIRECT_KINDS = {
7
+ text: 'text',
8
+ textarea: 'text',
9
+ richtext: 'richtext',
10
+ select: 'value',
11
+ radio: 'value',
12
+ number: 'value',
13
+ slot: 'slot'
14
+ };
15
+ function declaredKind(field) {
16
+ const metadata = field.metadata;
17
+ return metadata?.nodehive?.kind;
18
+ }
19
+ function propFromField(field, path, warnings) {
20
+ const declared = declaredKind(field);
21
+ if (declared !== undefined && !isKind(declared)) {
22
+ warnings.push(`${path}: declared kind "${String(declared)}" is unknown, exported as opaque`);
23
+ return {
24
+ kind: 'opaque'
25
+ };
26
+ }
27
+ const kind = declared ?? DIRECT_KINDS[field.type];
28
+ if (field.type === 'array') {
29
+ return {
30
+ kind: kind ?? 'array',
31
+ fields: propsFromFields(field.arrayFields, path, warnings)
32
+ };
33
+ }
34
+ if (field.type === 'object') {
35
+ return {
36
+ kind: kind ?? 'object',
37
+ fields: propsFromFields(field.objectFields, path, warnings)
38
+ };
39
+ }
40
+ if (kind) return {
41
+ kind
42
+ };
43
+ warnings.push(`${path}: "${field.type}" field without nodehive kind metadata, exported as opaque`);
44
+ return {
45
+ kind: 'opaque'
46
+ };
47
+ }
48
+ function propsFromFields(fields, path, warnings) {
49
+ const props = {};
50
+ for (const [name, field] of Object.entries(fields ?? {})) {
51
+ props[name] = propFromField(field, `${path}.${name}`, warnings);
52
+ }
53
+ return props;
54
+ }
55
+ export function generatePuckSchema(bundles) {
56
+ const warnings = [];
57
+ const schemaBundles = {};
58
+ for (const {
59
+ type,
60
+ dataField,
61
+ config
62
+ } of bundles) {
63
+ const components = {};
64
+ for (const [name, component] of Object.entries(config.components ?? {})) {
65
+ components[name] = {
66
+ props: propsFromFields(component.fields, `${type}: ${name}`, warnings)
67
+ };
68
+ }
69
+ schemaBundles[type] = {
70
+ dataField,
71
+ root: {
72
+ props: propsFromFields(config.root?.fields, `${type}: root`, warnings)
73
+ },
74
+ components
75
+ };
76
+ }
77
+ return {
78
+ version: PUCK_SCHEMA_VERSION,
79
+ bundles: schemaBundles,
80
+ warnings
81
+ };
82
+ }
83
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","names":["PUCK_SCHEMA_VERSION","KINDS","isKind","value","includes","DIRECT_KINDS","text","textarea","richtext","select","radio","number","slot","declaredKind","field","metadata","nodehive","kind","propFromField","path","warnings","declared","undefined","push","String","type","fields","propsFromFields","arrayFields","objectFields","props","name","Object","entries","generatePuckSchema","bundles","schemaBundles","dataField","config","components","component","root","version"],"sources":["../../../src/puck-editor/internal/schema.ts"],"sourcesContent":["import type { Config, Field } from '@puckeditor/core';\n\nexport const PUCK_SCHEMA_VERSION = 1;\n\nconst KINDS = [\n 'text',\n 'richtext',\n 'slot',\n 'array',\n 'object',\n 'media',\n 'entity',\n 'link',\n 'value',\n 'opaque',\n] as const;\n\nexport type PuckSchemaPropKind = (typeof KINDS)[number];\n\nexport type PuckSchemaProp = {\n kind: PuckSchemaPropKind;\n fields?: Record<string, PuckSchemaProp>;\n};\n\nexport type PuckSchemaComponent = {\n props: Record<string, PuckSchemaProp>;\n};\n\nexport type PuckSchemaBundle = {\n dataField: string;\n root: PuckSchemaComponent;\n components: Record<string, PuckSchemaComponent>;\n};\n\nexport type PuckSchema = {\n version: number;\n bundles: Record<string, PuckSchemaBundle>;\n warnings: string[];\n};\n\nexport type PuckSchemaBundleInput = {\n type: string;\n dataField: string;\n config: Config;\n};\n\nfunction isKind(value: unknown): value is PuckSchemaPropKind {\n return KINDS.includes(value as PuckSchemaPropKind);\n}\n\nconst DIRECT_KINDS: Record<string, PuckSchemaPropKind> = {\n text: 'text',\n textarea: 'text',\n richtext: 'richtext',\n select: 'value',\n radio: 'value',\n number: 'value',\n slot: 'slot',\n};\n\nfunction declaredKind(field: Field): unknown {\n const metadata = field.metadata as\n { nodehive?: { kind?: unknown } } | undefined;\n return metadata?.nodehive?.kind;\n}\n\nfunction propFromField(\n field: Field,\n path: string,\n warnings: string[]\n): PuckSchemaProp {\n const declared = declaredKind(field);\n if (declared !== undefined && !isKind(declared)) {\n warnings.push(\n `${path}: declared kind \"${String(declared)}\" is unknown, exported as opaque`\n );\n return { kind: 'opaque' };\n }\n const kind = declared ?? DIRECT_KINDS[field.type];\n if (field.type === 'array') {\n return {\n kind: kind ?? 'array',\n fields: propsFromFields(field.arrayFields, path, warnings),\n };\n }\n if (field.type === 'object') {\n return {\n kind: kind ?? 'object',\n fields: propsFromFields(field.objectFields, path, warnings),\n };\n }\n if (kind) return { kind };\n warnings.push(\n `${path}: \"${field.type}\" field without nodehive kind metadata, exported as opaque`\n );\n return { kind: 'opaque' };\n}\n\nfunction propsFromFields(\n fields: Record<string, Field> | undefined,\n path: string,\n warnings: string[]\n): Record<string, PuckSchemaProp> {\n const props: Record<string, PuckSchemaProp> = {};\n for (const [name, field] of Object.entries(fields ?? {})) {\n props[name] = propFromField(field, `${path}.${name}`, warnings);\n }\n return props;\n}\n\nexport function generatePuckSchema(\n bundles: PuckSchemaBundleInput[]\n): PuckSchema {\n const warnings: string[] = [];\n const schemaBundles: Record<string, PuckSchemaBundle> = {};\n for (const { type, dataField, config } of bundles) {\n const components: Record<string, PuckSchemaComponent> = {};\n for (const [name, component] of Object.entries(config.components ?? {})) {\n components[name] = {\n props: propsFromFields(\n component.fields as Record<string, Field> | undefined,\n `${type}: ${name}`,\n warnings\n ),\n };\n }\n schemaBundles[type] = {\n dataField,\n root: {\n props: propsFromFields(\n config.root?.fields as Record<string, Field> | undefined,\n `${type}: root`,\n warnings\n ),\n },\n components,\n };\n }\n return { version: PUCK_SCHEMA_VERSION, bundles: schemaBundles, warnings };\n}\n"],"mappings":"AAEA,OAAO,MAAMA,mBAAmB,GAAG,CAAC;AAEpC,MAAMC,KAAK,GAAG,CACZ,MAAM,EACN,UAAU,EACV,MAAM,EACN,OAAO,EACP,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,MAAM,EACN,OAAO,EACP,QAAQ,CACA;AA+BV,SAASC,MAAMA,CAACC,KAAc,EAA+B;EAC3D,OAAOF,KAAK,CAACG,QAAQ,CAACD,KAA2B,CAAC;AACpD;AAEA,MAAME,YAAgD,GAAG;EACvDC,IAAI,EAAE,MAAM;EACZC,QAAQ,EAAE,MAAM;EAChBC,QAAQ,EAAE,UAAU;EACpBC,MAAM,EAAE,OAAO;EACfC,KAAK,EAAE,OAAO;EACdC,MAAM,EAAE,OAAO;EACfC,IAAI,EAAE;AACR,CAAC;AAED,SAASC,YAAYA,CAACC,KAAY,EAAW;EAC3C,MAAMC,QAAQ,GAAGD,KAAK,CAACC,QACwB;EAC/C,OAAOA,QAAQ,EAAEC,QAAQ,EAAEC,IAAI;AACjC;AAEA,SAASC,aAAaA,CACpBJ,KAAY,EACZK,IAAY,EACZC,QAAkB,EACF;EAChB,MAAMC,QAAQ,GAAGR,YAAY,CAACC,KAAK,CAAC;EACpC,IAAIO,QAAQ,KAAKC,SAAS,IAAI,CAACpB,MAAM,CAACmB,QAAQ,CAAC,EAAE;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,GAAG,EAAE;EAC7B,MAAMgB,aAA+C,GAAG,CAAC,CAAC;EAC1D,KAAK,MAAM;IAAEX,IAAI;IAAEY,SAAS;IAAEC;EAAO,CAAC,IAAIH,OAAO,EAAE;IACjD,MAAMI,UAA+C,GAAG,CAAC,CAAC;IAC1D,KAAK,MAAM,CAACR,IAAI,EAAES,SAAS,CAAC,IAAIR,MAAM,CAACC,OAAO,CAACK,MAAM,CAACC,UAAU,IAAI,CAAC,CAAC,CAAC,EAAE;MACvEA,UAAU,CAACR,IAAI,CAAC,GAAG;QACjBD,KAAK,EAAEH,eAAe,CACpBa,SAAS,CAACd,MAAM,EAChB,GAAGD,IAAI,KAAKM,IAAI,EAAE,EAClBX,QACF;MACF,CAAC;IACH;IACAgB,aAAa,CAACX,IAAI,CAAC,GAAG;MACpBY,SAAS;MACTI,IAAI,EAAE;QACJX,KAAK,EAAEH,eAAe,CACpBW,MAAM,CAACG,IAAI,EAAEf,MAAM,EACnB,GAAGD,IAAI,QAAQ,EACfL,QACF;MACF,CAAC;MACDmB;IACF,CAAC;EACH;EACA,OAAO;IAAEG,OAAO,EAAE1C,mBAAmB;IAAEmC,OAAO,EAAEC,aAAa;IAAEhB;EAAS,CAAC;AAC3E","ignoreList":[]}
@@ -1,3 +1,4 @@
1
1
  export type { PuckApiConfig, PuckPublishContext, PuckPublishPageSettings, PuckPublishPayload, } from './internal/api/config.js';
2
2
  export { createPuckApi } from './internal/api/create-puck-api.js';
3
3
  export type { PuckBundleConfig, PuckContentModelInput, PuckTemplatesConfig, } from './internal/content-model.js';
4
+ export { generatePuckSchema, PUCK_SCHEMA_VERSION, type PuckSchema, type PuckSchemaBundle, type PuckSchemaBundleInput, type PuckSchemaComponent, type PuckSchemaProp, type PuckSchemaPropKind, } from './internal/schema.js';
@@ -1,4 +1,5 @@
1
1
  // Server entry: the handler factory for the catch-all API mount.
2
2
 
3
3
  export { createPuckApi } from "./internal/api/create-puck-api.js";
4
+ export { generatePuckSchema, PUCK_SCHEMA_VERSION } from "./internal/schema.js";
4
5
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["createPuckApi"],"sources":["../../src/puck-editor/server.ts"],"sourcesContent":["// Server entry: the handler factory for the catch-all API mount.\nexport type {\n PuckApiConfig,\n PuckPublishContext,\n PuckPublishPageSettings,\n PuckPublishPayload,\n} from './internal/api/config.ts';\nexport { createPuckApi } from './internal/api/create-puck-api.ts';\nexport type {\n PuckBundleConfig,\n PuckContentModelInput,\n PuckTemplatesConfig,\n} from './internal/content-model.ts';\n"],"mappings":"AAAA;;AAOA,SAASA,aAAa,QAAQ,mCAAmC","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["createPuckApi","generatePuckSchema","PUCK_SCHEMA_VERSION"],"sources":["../../src/puck-editor/server.ts"],"sourcesContent":["// Server entry: the handler factory for the catch-all API mount.\nexport type {\n PuckApiConfig,\n PuckPublishContext,\n PuckPublishPageSettings,\n PuckPublishPayload,\n} from './internal/api/config.ts';\nexport { createPuckApi } from './internal/api/create-puck-api.ts';\nexport type {\n PuckBundleConfig,\n PuckContentModelInput,\n PuckTemplatesConfig,\n} from './internal/content-model.ts';\nexport {\n generatePuckSchema,\n PUCK_SCHEMA_VERSION,\n type PuckSchema,\n type PuckSchemaBundle,\n type PuckSchemaBundleInput,\n type PuckSchemaComponent,\n type PuckSchemaProp,\n type PuckSchemaPropKind,\n} from './internal/schema.ts';\n"],"mappings":"AAAA;;AAOA,SAASA,aAAa,QAAQ,mCAAmC;AAMjE,SACEC,kBAAkB,EAClBC,mBAAmB,QAOd,sBAAsB","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodehive/nextjs",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "NodeHive Next.js infrastructure modules: auth, puck-editor, visual-editor, smart-actions",
5
5
  "license": "MIT",
6
6
  "author": "NETNODE AG <info@netnode.ch>",