@bison-lab/payload-core 5.6.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -645,9 +645,10 @@ wraps `@payloadcms/plugin-redirects` for `pages` only (permanent 308) and
645
645
  collapses chains when a published slug changes. The plugin stores the
646
646
  rows; the site still has to serve them. Pin the plugin to the same
647
647
  version as `payload`, then `payload generate:importmap`,
648
- `payload generate:types`, and `payload migrate:create`. Create follows the Content tick. Update without Publish is
649
- constrained to `_status: draft` — an Author can save a draft and cannot
650
- publish or edit a live page. Users sit under Settings next to Roles,
648
+ `payload generate:types`, and `payload migrate:create`. Create and update follow the Content tick;
649
+ only the Publish grant writes the live page (a publish, a save without
650
+ `?draft=true`, every version restore), held by the shared
651
+ `roles/publish-gate` hooks (#330). Users sit under Settings next to Roles,
651
652
  take `secureCookies`, and offer whatever rows the Global (or the seed
652
653
  plus the same `extras`) has. `users.roles` and `users.allowedFeatures`
653
654
  set `saveToJWT: true`. The checklist labels are the editable names.
@@ -708,7 +709,9 @@ so an existing one-document row does not move. Footer is
708
709
  Postgres's 63-character identifier cap the same way `nav` did. Both sit
709
710
  in `admin.group: "Navigation"` until a Developer moves them from Admin
710
711
  nav. One Features tick (`navigation`, passed as a `createFeatures`
711
- extra). Publish still needs the Publish tick. `getNavigation({ payload,
712
+ extra; no seed role holds it). The tick saves drafts; a publish, a save
713
+ without `?draft=true` and every version restore need the Publish tick
714
+ (`roles/publish-gate`, #330). `getNavigation({ payload,
712
715
  draft })` finds both and returns `{ header, footer, bar }`; a site with
713
716
  more than one locale adds `locale` (and `fallbackLocale`) so the labels
714
717
  read in it.
@@ -910,7 +913,7 @@ the switcher/hreflang filter; `GET /api/translation/locales` serves it to an
910
913
  edge runtime. `localizeExistingContent` is the one-to-several locale data
911
914
  migration: it runs the generated SQL with every `DROP COLUMN` / `DROP TYPE`
912
915
  moved last and each moving column copied into `<table>_locales` first.
913
- It also sets the default locale on the new `locale` column of `_rels` / `_texts` / `_numbers` rows whose `path` is a localized field (`isLocalizedPath` over the migration's `payload.config`), and stops when such rows exist without it. Postgres only. `pnpm --filter @bison-lab/payload-core test:postgres` runs it against a local Postgres with recorded `migrate:create` output (`src/__tests__/fixtures/localize/`); the normal suite skips it.
916
+ It also sets the default locale on the new `locale` column of `_rels` / `_texts` / `_numbers` rows whose `path` is a localized field (`isLocalizedPath` over the migration's `payload.config`), and stops when such rows exist without it. Postgres only. `pnpm --filter @bison-lab/payload-core test:postgres` runs it against a local Postgres with recorded `migrate:create` output (`src/__tests__/fixtures/localize/`); the normal suite skips it. The same command also boots a real Payload on a scratch database (`@payloadcms/db-postgres`, a dev dependency pinned to the Payload version) to hold the Interface text Global's behavior that FakePayload only copies: a never-saved Global reading as a draft, and a version restore writing the live row (`interface-text-postgres.test.ts`, #305 / #309).
914
917
 
915
918
  ### Jobs, usage and failures (#295, #296)
916
919
 
@@ -668,6 +668,45 @@ function hideUnlessFeature(slug) {
668
668
  };
669
669
  }
670
670
  //#endregion
671
+ //#region src/roles/publish-gate.ts
672
+ /**
673
+ * Without Publish, an update must be a draft save (`draft: true`;
674
+ * `?draft=true` over REST, which the admin's Save draft and autosave send),
675
+ * and a version restore is refused outright: a restore writes the live row
676
+ * even with `draft: true` (Payload only marks it a draft first). Writes with
677
+ * no user or with `overrideAccess` are the server's own and pass.
678
+ */
679
+ async function draftSavesOnly({ args, operation, req }) {
680
+ if (operation !== "update" && operation !== "restoreVersion") return args;
681
+ const write = args ?? {};
682
+ if (write.overrideAccess || !req.user) return args;
683
+ if (operation === "update" && write.draft === true && !write.publishAllLocales && !write.publishSpecificLocale && !write.unpublishAllLocales) return args;
684
+ if (await Promise.resolve(canPublish({ req }))) return args;
685
+ throw new Forbidden();
686
+ }
687
+ /** Publishing (`_status: 'published'`) needs the Publish grant. */
688
+ async function refusePublish({ data, req }) {
689
+ if (data?._status !== "published" || !req.user) return data;
690
+ if (await Promise.resolve(canPublish({ req }))) return data;
691
+ throw new Forbidden();
692
+ }
693
+ /**
694
+ * Update access for a drafted document: `base` (the Content or feature
695
+ * tick), refused for data that publishes unless the login holds Publish.
696
+ * Enforcement is the two hooks; this is what hides the admin's Publish
697
+ * button, which Payload shows from `access.update` called with
698
+ * `_status: 'published'` (and draft editing from `_status: 'draft'`).
699
+ */
700
+ function updateUnlessPublishing(base) {
701
+ return async (args) => {
702
+ if (!await Promise.resolve(base(args))) return false;
703
+ if (args.data?._status !== "published") return true;
704
+ return Boolean(await Promise.resolve(canPublish({ req: args.req })));
705
+ };
706
+ }
707
+ const draftSavesOnlyWithoutPublish = draftSavesOnly;
708
+ const refusePublishWithoutGrant = refusePublish;
709
+ //#endregion
671
710
  //#region src/translate/fields.ts
672
711
  const isDoc = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
673
712
  const asRows = (value) => Array.isArray(value) ? value.filter(isDoc) : void 0;
@@ -3704,12 +3743,6 @@ function getMessages(payload, locale, options = {}) {
3704
3743
  value.catch(() => byLocale.delete(locale));
3705
3744
  return value;
3706
3745
  }
3707
- /** Publishing needs the Publish grant, as on Pages and the Header; Content alone saves drafts. */
3708
- const refusePublishWithoutGrant = async ({ data, req }) => {
3709
- if (data?._status !== "published" || !req.user) return data;
3710
- if (await Promise.resolve(canPublish({ req }))) return data;
3711
- throw new Forbidden();
3712
- };
3713
3746
  const clearMessages = ({ doc, req }) => {
3714
3747
  invalidateMessages(req.payload);
3715
3748
  return doc;
@@ -3718,7 +3751,9 @@ const clearMessages = ({ doc, req }) => {
3718
3751
  * The Interface text Global: one row per message, key shared by every
3719
3752
  * locale, text localized. Drafts on, so a publish is what re-translates
3720
3753
  * changed English (the usual rules). The Content grant saves drafts; the
3721
- * Publish grant publishes, as on Pages and the Header.
3754
+ * Publish grant publishes, as on Pages and the Header, and is the only
3755
+ * grant that writes the live text any other way (a plain update, a version
3756
+ * restore).
3722
3757
  */
3723
3758
  function interfaceTextGlobal() {
3724
3759
  return {
@@ -3730,13 +3765,14 @@ function interfaceTextGlobal() {
3730
3765
  },
3731
3766
  access: {
3732
3767
  read: ({ req }) => isAuthenticated(req.user),
3733
- update: (args) => canUseFeature("content")(args)
3768
+ update: updateUnlessPublishing((args) => canUseFeature("content")(args))
3734
3769
  },
3735
3770
  versions: {
3736
3771
  drafts: true,
3737
3772
  max: 50
3738
3773
  },
3739
3774
  hooks: {
3775
+ beforeOperation: [draftSavesOnlyWithoutPublish],
3740
3776
  beforeChange: [refusePublishWithoutGrant],
3741
3777
  afterChange: [clearMessages]
3742
3778
  },
@@ -3771,6 +3807,33 @@ function interfaceTextGlobal() {
3771
3807
  };
3772
3808
  }
3773
3809
  /**
3810
+ * Judged from the newest version row, not `findGlobal({ draft: true })`: a
3811
+ * Global that was never saved has no row, and Payload reads it back with the
3812
+ * `_status` default, `'draft'`, so that read refused a first import (#305).
3813
+ * A caller's `payload` without `findGlobalVersions` (a hand-built wrapper
3814
+ * written for the earlier signature) keeps the old read, and with it the old
3815
+ * refusal of a never-saved Global; pass `req` instead of wrapping.
3816
+ */
3817
+ async function hasUnpublishedDraft(payload, req) {
3818
+ if (typeof payload.findGlobalVersions !== "function") return (await payload.findGlobal({
3819
+ slug: INTERFACE_TEXT_SLUG,
3820
+ depth: 0,
3821
+ overrideAccess: true,
3822
+ draft: true,
3823
+ ...req
3824
+ }))?._status === "draft";
3825
+ const { docs } = await payload.findGlobalVersions({
3826
+ slug: INTERFACE_TEXT_SLUG,
3827
+ sort: "-updatedAt",
3828
+ limit: 1,
3829
+ pagination: false,
3830
+ depth: 0,
3831
+ overrideAccess: true,
3832
+ ...req
3833
+ });
3834
+ return (docs[0]?.version)?._status === "draft";
3835
+ }
3836
+ /**
3774
3837
  * The migration path from `messages/<locale>.json`: the source locale's
3775
3838
  * file sets the keys and fills blank English, every other file fills blank
3776
3839
  * text in its locale. Anything already in the CMS is kept, so running it
@@ -3780,13 +3843,19 @@ function interfaceTextGlobal() {
3780
3843
  * `context: { autoTranslate: false }`, so importing translates nothing;
3781
3844
  * blank strings left over fill on the next publish or backfill.
3782
3845
  *
3846
+ * In a migration, pass its `req` so every read and write joins the
3847
+ * migration's transaction and sees the tables it just created.
3848
+ *
3783
3849
  * ```ts
3784
3850
  * import en from "../src/messages/en.json";
3785
3851
  * import es from "../src/messages/es.json";
3786
- * await importMessages(payload, { en, es });
3852
+ * export async function up({ payload, req }: MigrateUpArgs) {
3853
+ * await importMessages(payload, { en, es }, { req });
3854
+ * }
3787
3855
  * ```
3788
3856
  */
3789
3857
  async function importMessages(payload, files, options = {}) {
3858
+ const req = options.req ? { req: options.req } : {};
3790
3859
  const localization = payload.config.localization;
3791
3860
  const source = options.sourceLocale ?? (localization ? localization.defaultLocale : "en");
3792
3861
  const sourceFile = files[source];
@@ -3802,7 +3871,8 @@ async function importMessages(payload, files, options = {}) {
3802
3871
  fallbackLocale: false,
3803
3872
  depth: 0,
3804
3873
  overrideAccess: true,
3805
- draft: true
3874
+ draft: true,
3875
+ ...req
3806
3876
  })).messages ?? [];
3807
3877
  const write = async (locale, rows) => {
3808
3878
  await payload.updateGlobal({
@@ -3814,16 +3884,12 @@ async function importMessages(payload, files, options = {}) {
3814
3884
  },
3815
3885
  depth: 0,
3816
3886
  overrideAccess: true,
3817
- context: { autoTranslate: false }
3887
+ context: { autoTranslate: false },
3888
+ ...req
3818
3889
  });
3819
3890
  };
3820
3891
  const blank = (value) => typeof value !== "string" || value.trim() === "";
3821
- if ((await payload.findGlobal({
3822
- slug: "interface-text",
3823
- depth: 0,
3824
- overrideAccess: true,
3825
- draft: true
3826
- }))?._status === "draft") throw new Error("importMessages: Interface text has an unpublished draft. Publish or discard it in the admin, then import again, so the import does not put that draft live.");
3892
+ if (await hasUnpublishedDraft(payload, req)) throw new Error("importMessages: Interface text has an unpublished draft. Publish or discard it in the admin, then import again, so the import does not put that draft live.");
3827
3893
  const flatSource = flattenMessages(sourceFile);
3828
3894
  const rows = (await read(source)).map((row) => ({ ...row }));
3829
3895
  const byKey = new Map(rows.map((row) => [row.key, row]));
@@ -4096,6 +4162,6 @@ function withJobsOnSwitch(global) {
4096
4162
  };
4097
4163
  }
4098
4164
  //#endregion
4099
- export { LIBRARY_DEFAULT_LOCALE as $, seedRoleRows as $t, TRANSLATE_NOW as A, isAuthenticated as At, TRANSLATION_STATUS_BAR as B, LAST_USERS_TICK_MESSAGE as Bt, isAutosave as C, PACKAGE_FEATURES as Cn, getRolesMatrix as Ct, shouldSkipUndraftedTranslation as D, isLockedFeature as Dn, hideUnlessDeveloper as Dt, shouldSkipDraftedTranslation as E, isFeatureSlug as En, hasRole as Et, TRANSLATION_ACTIVITY_PANEL as F, DEFAULT_ROLE_MATRIX as Ft, FAILURE_ADVICE as G, applyRoleSlugsFromNames as Gt, readTranslationSettings as H, ROLES_FIELD_DESCRIPTION as Ht, TRANSLATION_GRANT as I, DEVELOPER_DESCRIPTION as It, monthKey as J, normalizeStoredRoles as Jt, RATE_LIMIT_STREAK as K, defaultRolesFieldValue as Kt, TRANSLATION_KEY_PANEL as L, DUPLICATE_ROLE_NAME_MESSAGE as Lt, BISON_TRANSLATION_CONTEXT as M, isDeveloperTab as Mt, readTranslateState as N, isPrivilegedRole as Nt, TRANSACTION_TIMEOUT_MS as O, isPackageFeatureSlug as On, isAdmin as Ot, withTranslator as P, storedRoles as Pt, ACTIVE_LOCALES_CACHE_MS as Q, roleSelectOptions as Qt, TRANSLATION_SETTINGS_SLUG as R, DUPLICATE_ROLE_SLUG_MESSAGE as Rt, startJob as S, FEATURE_GROUP_LABELS as Sn, developerOnlyAccess as St, localizedCopyUnchanged as T, isFeatureGroupId as Tn, hasGrant as Tt, resolveModel as U, ROLES_GLOBAL_DESCRIPTION as Ut, invalidateTranslationSettings as V, MISSING_SEED_ROLES_MESSAGE as Vt, siteFromInstructions as W, ROLES_SLUG as Wt, usageHistory as X, resetRolesMatrix as Xt, recordUsage as Y, parseRolesMatrix as Yt, usageThisMonth as Z, roleDescription as Zt, frozenWordForce as _, roleLabel as _n, hideUnlessFeature as _t, MESSAGES_CACHE_MS as a, parseFeaturesMatrix as an, invalidateActiveLocales as at, runJobSlice as b, FEATURES_SLUG as bn, canManageContent as bt, importMessages as c, CAPABILITIES as cn, encryptApiKey as ct, unflattenMessages as d, ROLES as dn, sameRow as dt, validateRolesMatrix as en, LIBRARY_LOCALES as et, translationSettingsEndpoints as f, ROLE_LABELS as fn, translationJob as ft, estimateJob as g, isRoleSlug as gn, hasFeature as gt, claimJob as h, isRoleName as hn, getFeaturesMatrix as ht, INTERFACE_TEXT_SLUG as i, featureGroupLabel as in, inactiveLocaleRedirect as it, translateDocument as j, isDeveloper as jt, runAfterCommit as k, isAdminOrSelf as kt, interfaceTextGlobal as l, CAPABILITY_FEATURES as ln, resolveApiKey as lt, TRANSLATION_JOBS_SLUG as m, isRole as mn, canUseFeature as mt, hasLocalizedFields as n, defaultFeaturesFieldValue as nn, activeAlternates as nt, flattenMessages as o, stampFeatureCatalogue as on, withLibraryLocales as ot, LEASE_MS as p, THEME_FEATURE_SLUGS as pn, allowedFeaturesForUser as pt, TRANSLATION_USAGE_SLUG as q, grantsFromStoredRole as qt, translation as r, featureCatalogue as rn, activeLocales as rt, getMessages as s, validateFeaturesMatrix as sn, decryptApiKey as st, applyTranslation as t, MISSING_PACKAGE_FEATURES_MESSAGE as tn, LIBRARY_LOCALE_CODES as tt, invalidateMessages as u, DEFAULT_ROLE_GRANTS as un, collectLocalizedStrings as ut, jobView as v, sanitizeRoleNameInput as vn, authenticatedOrPublished as vt, draftedTranslationDecision as w, PACKAGE_FEATURE_SLUGS as wn, hasCapability as wt, startBackfill as x, FEATURE_GROUPS as xn, canPublish as xt, resumeStaleJobs as y, slugifyRoleName as yn, canManageBrand as yt, TRANSLATION_STATE_SLUG as z, INVALID_ROLE_NAME_MESSAGE as zt };
4165
+ export { LIBRARY_DEFAULT_LOCALE as $, resetRolesMatrix as $t, TRANSLATE_NOW as A, isLockedFeature as An, hideUnlessDeveloper as At, TRANSLATION_STATUS_BAR as B, DUPLICATE_ROLE_NAME_MESSAGE as Bt, isAutosave as C, FEATURES_SLUG as Cn, canManageContent as Ct, shouldSkipUndraftedTranslation as D, PACKAGE_FEATURE_SLUGS as Dn, hasCapability as Dt, shouldSkipDraftedTranslation as E, PACKAGE_FEATURES as En, getRolesMatrix as Et, TRANSLATION_ACTIVITY_PANEL as F, isDeveloperTab as Ft, FAILURE_ADVICE as G, ROLES_FIELD_DESCRIPTION as Gt, readTranslationSettings as H, INVALID_ROLE_NAME_MESSAGE as Ht, TRANSLATION_GRANT as I, isPrivilegedRole as It, monthKey as J, applyRoleSlugsFromNames as Jt, RATE_LIMIT_STREAK as K, ROLES_GLOBAL_DESCRIPTION as Kt, TRANSLATION_KEY_PANEL as L, storedRoles as Lt, BISON_TRANSLATION_CONTEXT as M, isAdminOrSelf as Mt, readTranslateState as N, isAuthenticated as Nt, TRANSACTION_TIMEOUT_MS as O, isFeatureGroupId as On, hasGrant as Ot, withTranslator as P, isDeveloper as Pt, ACTIVE_LOCALES_CACHE_MS as Q, parseRolesMatrix as Qt, TRANSLATION_SETTINGS_SLUG as R, DEFAULT_ROLE_MATRIX as Rt, startJob as S, slugifyRoleName as Sn, canManageBrand as St, localizedCopyUnchanged as T, FEATURE_GROUP_LABELS as Tn, developerOnlyAccess as Tt, resolveModel as U, LAST_USERS_TICK_MESSAGE as Ut, invalidateTranslationSettings as V, DUPLICATE_ROLE_SLUG_MESSAGE as Vt, siteFromInstructions as W, MISSING_SEED_ROLES_MESSAGE as Wt, usageHistory as X, grantsFromStoredRole as Xt, recordUsage as Y, defaultRolesFieldValue as Yt, usageThisMonth as Z, normalizeStoredRoles as Zt, frozenWordForce as _, isRole as _n, canUseFeature as _t, MESSAGES_CACHE_MS as a, defaultFeaturesFieldValue as an, invalidateActiveLocales as at, runJobSlice as b, roleLabel as bn, hideUnlessFeature as bt, importMessages as c, parseFeaturesMatrix as cn, encryptApiKey as ct, unflattenMessages as d, CAPABILITIES as dn, sameRow as dt, roleDescription as en, LIBRARY_LOCALES as et, translationSettingsEndpoints as f, CAPABILITY_FEATURES as fn, translationJob as ft, estimateJob as g, THEME_FEATURE_SLUGS as gn, allowedFeaturesForUser as gt, claimJob as h, ROLE_LABELS as hn, updateUnlessPublishing as ht, INTERFACE_TEXT_SLUG as i, MISSING_PACKAGE_FEATURES_MESSAGE as in, inactiveLocaleRedirect as it, translateDocument as j, isPackageFeatureSlug as jn, isAdmin as jt, runAfterCommit as k, isFeatureSlug as kn, hasRole as kt, interfaceTextGlobal as l, stampFeatureCatalogue as ln, resolveApiKey as lt, TRANSLATION_JOBS_SLUG as m, ROLES as mn, refusePublishWithoutGrant as mt, hasLocalizedFields as n, seedRoleRows as nn, activeAlternates as nt, flattenMessages as o, featureCatalogue as on, withLibraryLocales as ot, LEASE_MS as p, DEFAULT_ROLE_GRANTS as pn, draftSavesOnlyWithoutPublish as pt, TRANSLATION_USAGE_SLUG as q, ROLES_SLUG as qt, translation as r, validateRolesMatrix as rn, activeLocales as rt, getMessages as s, featureGroupLabel as sn, decryptApiKey as st, applyTranslation as t, roleSelectOptions as tn, LIBRARY_LOCALE_CODES as tt, invalidateMessages as u, validateFeaturesMatrix as un, collectLocalizedStrings as ut, jobView as v, isRoleName as vn, getFeaturesMatrix as vt, draftedTranslationDecision as w, FEATURE_GROUPS as wn, canPublish as wt, startBackfill as x, sanitizeRoleNameInput as xn, authenticatedOrPublished as xt, resumeStaleJobs as y, isRoleSlug as yn, hasFeature as yt, TRANSLATION_STATE_SLUG as z, DEVELOPER_DESCRIPTION as zt };
4100
4166
 
4101
- //# sourceMappingURL=capability-CAXtTcSU.mjs.map
4167
+ //# sourceMappingURL=capability-B3Mk0KRh.mjs.map