@domandigital/sanity-copy 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @domandigital/sanity-copy
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3eb1560: CommonJS consumers now get the CommonJS type declarations. The `exports` map put a top-level `types` (the ESM `.d.ts`) ahead of `require`, so TypeScript resolving a `require` under `node16` stopped at the ESM file ("Masquerading as ESM" in @arethetypeswrong/cli). `types` now sits inside `import` and `require` separately. Runtime behaviour is unchanged.
8
+
9
+ Requires Node 22.12 or later (`engines.node`). Node 20 reached end of life on 2026-04-30. Also declares `sideEffects` so bundlers can tree-shake (craft keeps its CSS).
10
+
11
+ - a5868b0: Localised content, hidden fields, and an opt-in publish guard.
12
+
13
+ - `languages` option (e.g. `["en"]`): copy in other languages is skipped. The language comes from an internationalized-array item's `language` field (plugin v5), or from its `_key` (v4); from a field-level translation object whose keys are all two-letter language tags; or from a document's `language` field. `"en"` covers `en-GB` and `en_US`. Unset: unchanged.
14
+ - `withCopyGuard(publishAction)`: opt-in. Publishing stays disabled while the document has a blocking-tier finding, and the finding shows as the tooltip. It returns the Studio's own action type. No Sanity import.
15
+ - `withCopyCheck` never reads fields the schema hides with a static `hidden: true`, inline or through a named object type (new `hiddenPaths` option underneath). `hidden` functions are not evaluated.
16
+ - `language` and `locale` are skipped fields; mixed-case locale tags such as `nb_NO` are no longer read as copy; `assist.instruction.context` (AI Assist instructions) is an excluded type.
17
+ - The Studio validation cache is keyed on the collected copy, so editing a link or a slug no longer re-runs the check.
18
+
19
+ ### Patch Changes
20
+
21
+ - Updated dependencies [e2ea0e8]
22
+ - Updated dependencies [3eb1560]
23
+ - @domandigital/craft@0.11.0
24
+
3
25
  ## 0.3.0
4
26
 
5
27
  ### Minor Changes
package/README.md CHANGED
@@ -11,8 +11,11 @@ belongs.
11
11
 
12
12
  ## In a Studio
13
13
 
14
- Works in any Sanity Studio, v3 or later. Nothing in it is specific to one
15
- site. Two steps:
14
+ Works in any Sanity Studio, v3 or later. It uses only `Rule.custom()`,
15
+ `Rule.warning()` and plain document-action functions, and imports nothing from
16
+ Sanity, so no Studio version is pinned. Its tests run against stand-ins for
17
+ those shapes, not a live Studio. Nothing in it is specific to one site. Two
18
+ steps:
16
19
 
17
20
  1. `pnpm add @domandigital/sanity-copy` (or npm, or yarn) in the Studio's app.
18
21
  2. Wrap the types array in `sanity.config.ts`, as below.
@@ -40,13 +43,53 @@ Options, all optional:
40
43
 
41
44
  | Option | Default | What it does |
42
45
  | --- | --- | --- |
43
- | `excludeTypes` | `testimonial`, `review`, `proofQuote`, `quote` | Never checked. A person's own words are exempt from every house rule. |
44
- | `skipFields` | `slug`, `url`, `href`, `link`, `email`, `phone`, ids, enums | Never read, at any depth. |
46
+ | `excludeTypes` | `testimonial`, `review`, `proofQuote`, `quote`, `assist.instruction.context` | Never checked. A person's own words are exempt from every house rule, and AI Assist instruction documents are prompts, not copy. |
47
+ | `skipFields` | `slug`, `url`, `href`, `link`, `email`, `phone`, `language`, `locale`, ids, enums | Never read, at any depth. |
45
48
  | `review` | `true` | Show the review and density tiers as well as the house rules. |
49
+ | `languages` | every language | Check only these, e.g. `["en"]`. See below. |
50
+ | `hiddenPaths` | from the schema | Dot paths never read. `withCopyCheck` fills this in from every static `hidden: true`. |
46
51
 
47
52
  What is read: strings, Portable Text (a block's spans joined, so a template
48
53
  split across spans is still caught), and the alt text and caption of images.
49
- What is not: slugs, links, references, enum values, asset data.
54
+ What is not: slugs, links, references, enum values, language tags, asset data,
55
+ and fields the schema hides with `hidden: true`. A `hidden` function is not
56
+ evaluated: it is decided per document and per editor, and the check has no way
57
+ to know the answer for a nested field, so those fields are still read.
58
+
59
+ ### Localised content
60
+
61
+ The rules are English. On a localised Studio, pass `languages: ["en"]` so the
62
+ other languages are left alone (`"en"` also covers `en-GB` and `en_US`). Four
63
+ shapes are recognised:
64
+
65
+ | Shape | Example | How the language is found |
66
+ | --- | --- | --- |
67
+ | sanity-plugin-internationalized-array v5 | `[{ _key: "k8f2a", language: "fr", value }]` | the item's `language` field |
68
+ | the same plugin, v4 and earlier | `[{ _key: "fr", value }]` | the item's `_key` |
69
+ | field-level translation | `{ en: "...", fr: "..." }` | the object key, when every key is a two-letter language tag |
70
+ | @sanity/document-internationalization | `{ _type: "page", language: "fr" }` | the document's `language` field |
71
+
72
+ ### Blocking publish (opt-in)
73
+
74
+ Everything above warns. A Studio that wants the house rules enforced can wrap
75
+ the publish action, which then stays disabled while the document has a
76
+ blocking-tier finding, with the finding as its tooltip. The review tier never
77
+ blocks.
78
+
79
+ ```ts
80
+ import { withCopyCheck, withCopyGuard } from "@domandigital/sanity-copy";
81
+
82
+ export default defineConfig({
83
+ schema: { types: withCopyCheck(schemaTypes) },
84
+ document: {
85
+ actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
86
+ },
87
+ });
88
+ ```
89
+
90
+ The original action is always called, so its behaviour is unchanged apart from
91
+ `disabled` and the tooltip. Excluded types (testimonials and the rest) are never
92
+ blocked.
50
93
 
51
94
  ## Sweeping a whole dataset
52
95
 
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@ import { readFileSync } from "fs";
5
5
 
6
6
  // src/core.ts
7
7
  import { applyHouseGate, checkCopy, findClaims } from "@domandigital/craft";
8
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
8
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
9
9
  var DEFAULT_SKIP_FIELDS = [
10
10
  "slug",
11
11
  "url",
@@ -29,17 +29,35 @@ var DEFAULT_SKIP_FIELDS = [
29
29
  "script",
30
30
  "schema",
31
31
  "jsonLd",
32
- "canonical"
32
+ "canonical",
33
+ "language",
34
+ "locale"
33
35
  ];
34
36
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
35
37
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
36
38
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
37
39
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
40
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
41
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
42
+ function languageWanted(tag, wanted) {
43
+ const t = tag.toLowerCase().replace(/_/g, "-");
44
+ return wanted.some((w) => {
45
+ const base = w.toLowerCase().replace(/_/g, "-");
46
+ return t === base || t.startsWith(`${base}-`);
47
+ });
48
+ }
49
+ function itemLanguage(item) {
50
+ if (typeof item.language === "string") return item.language;
51
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
52
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
53
+ return void 0;
54
+ }
38
55
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
39
56
  function notCopy(text) {
40
57
  const t = text.trim();
41
58
  if (!t) return true;
42
59
  if (/^[a-z0-9_-]+$/.test(t)) return true;
60
+ if (LANGUAGE_TAG.test(t)) return true;
43
61
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
44
62
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
45
63
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -58,7 +76,13 @@ function blockText(block) {
58
76
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
59
77
  function collectCopy(doc, options = {}) {
60
78
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
79
+ const hidden = new Set(options.hiddenPaths ?? []);
80
+ const languages = options.languages;
61
81
  const pieces = [];
82
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
83
+ return pieces;
84
+ }
85
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
62
86
  const walk = (value, path) => {
63
87
  if (typeof value === "string") {
64
88
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -66,6 +90,10 @@ function collectCopy(doc, options = {}) {
66
90
  }
67
91
  if (Array.isArray(value)) {
68
92
  value.forEach((item, i) => {
93
+ if (languages && isRecord(item)) {
94
+ const language = itemLanguage(item);
95
+ if (language && !languageWanted(language, languages)) return;
96
+ }
69
97
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
70
98
  const text = blockText(item);
71
99
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -78,9 +106,15 @@ function collectCopy(doc, options = {}) {
78
106
  if (!isRecord(value)) return;
79
107
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
80
108
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
109
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
110
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
81
111
  for (const [key, child] of Object.entries(value)) {
82
112
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
83
- walk(child, [...path, key]);
113
+ if (localeMap && !languageWanted(key, languages)) continue;
114
+ const childPath = [...path, key];
115
+ const dotted = fieldPath(childPath);
116
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
117
+ walk(child, childPath);
84
118
  }
85
119
  };
86
120
  walk(doc, []);
package/dist/index.cjs CHANGED
@@ -28,13 +28,14 @@ __export(index_exports, {
28
28
  describeFinding: () => describeFinding,
29
29
  documentClaims: () => documentClaims,
30
30
  pathToString: () => pathToString,
31
- withCopyCheck: () => withCopyCheck
31
+ withCopyCheck: () => withCopyCheck,
32
+ withCopyGuard: () => withCopyGuard
32
33
  });
33
34
  module.exports = __toCommonJS(index_exports);
34
35
 
35
36
  // src/core.ts
36
37
  var import_craft = require("@domandigital/craft");
37
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
38
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
38
39
  var DEFAULT_SKIP_FIELDS = [
39
40
  "slug",
40
41
  "url",
@@ -58,17 +59,35 @@ var DEFAULT_SKIP_FIELDS = [
58
59
  "script",
59
60
  "schema",
60
61
  "jsonLd",
61
- "canonical"
62
+ "canonical",
63
+ "language",
64
+ "locale"
62
65
  ];
63
66
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
64
67
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
65
68
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
66
69
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
70
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
71
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
72
+ function languageWanted(tag, wanted) {
73
+ const t = tag.toLowerCase().replace(/_/g, "-");
74
+ return wanted.some((w) => {
75
+ const base = w.toLowerCase().replace(/_/g, "-");
76
+ return t === base || t.startsWith(`${base}-`);
77
+ });
78
+ }
79
+ function itemLanguage(item) {
80
+ if (typeof item.language === "string") return item.language;
81
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
82
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
83
+ return void 0;
84
+ }
67
85
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
68
86
  function notCopy(text) {
69
87
  const t = text.trim();
70
88
  if (!t) return true;
71
89
  if (/^[a-z0-9_-]+$/.test(t)) return true;
90
+ if (LANGUAGE_TAG.test(t)) return true;
72
91
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
73
92
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
74
93
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -87,7 +106,13 @@ function blockText(block) {
87
106
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
88
107
  function collectCopy(doc, options = {}) {
89
108
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
109
+ const hidden = new Set(options.hiddenPaths ?? []);
110
+ const languages = options.languages;
90
111
  const pieces = [];
112
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
113
+ return pieces;
114
+ }
115
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
91
116
  const walk = (value, path) => {
92
117
  if (typeof value === "string") {
93
118
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -95,6 +120,10 @@ function collectCopy(doc, options = {}) {
95
120
  }
96
121
  if (Array.isArray(value)) {
97
122
  value.forEach((item, i) => {
123
+ if (languages && isRecord(item)) {
124
+ const language = itemLanguage(item);
125
+ if (language && !languageWanted(language, languages)) return;
126
+ }
98
127
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
99
128
  const text = blockText(item);
100
129
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -107,9 +136,15 @@ function collectCopy(doc, options = {}) {
107
136
  if (!isRecord(value)) return;
108
137
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
109
138
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
139
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
140
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
110
141
  for (const [key, child] of Object.entries(value)) {
111
142
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
112
- walk(child, [...path, key]);
143
+ if (localeMap && !languageWanted(key, languages)) continue;
144
+ const childPath = [...path, key];
145
+ const dotted = fieldPath(childPath);
146
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
147
+ walk(child, childPath);
113
148
  }
114
149
  };
115
150
  walk(doc, []);
@@ -163,10 +198,11 @@ function pathToString(path) {
163
198
 
164
199
  // src/schema.ts
165
200
  function copyCheckRule(rule, options = {}) {
166
- let lastInput = "";
201
+ let lastInput;
167
202
  let lastResult = true;
168
203
  return rule.custom((doc) => {
169
- const input = JSON.stringify(doc ?? null);
204
+ const type = doc !== null && typeof doc === "object" ? doc._type : void 0;
205
+ const input = JSON.stringify([type, collectCopy(doc, options)]);
170
206
  if (input === lastInput) return lastResult;
171
207
  lastInput = input;
172
208
  const findings = checkDocumentCopy(doc, options);
@@ -174,19 +210,60 @@ function copyCheckRule(rule, options = {}) {
174
210
  return lastResult;
175
211
  }).warning();
176
212
  }
213
+ function staticHiddenPaths(type, byName, prefix = "", seen = /* @__PURE__ */ new Set()) {
214
+ const own = Array.isArray(type.fields) ? type.fields : void 0;
215
+ const named = typeof type.type === "string" ? byName.get(type.type) : void 0;
216
+ const fields = own ?? (named && Array.isArray(named.fields) ? named.fields : []);
217
+ if (!own && named && typeof type.type === "string") {
218
+ if (seen.has(type.type)) return [];
219
+ seen = new Set(seen).add(type.type);
220
+ }
221
+ const paths = [];
222
+ for (const field of fields) {
223
+ if (typeof field?.name !== "string") continue;
224
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
225
+ if (field.hidden === true) paths.push(path);
226
+ else paths.push(...staticHiddenPaths(field, byName, path, seen));
227
+ }
228
+ return paths;
229
+ }
177
230
  var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
178
231
  function withCopyCheck(types, options = {}) {
179
232
  const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
233
+ const byName = new Map(types.map((t) => [t.name, t]));
180
234
  return types.map((t) => {
181
235
  if (t.type !== "document" || excluded.has(t.name)) return t;
236
+ const hiddenPaths = [...options.hiddenPaths ?? [], ...staticHiddenPaths({ fields: t.fields }, byName)];
237
+ const typeOptions = hiddenPaths.length > 0 ? { ...options, hiddenPaths } : options;
182
238
  const existing = t.validation;
183
239
  const validation = (rule, context) => [
184
240
  ...asArray(typeof existing === "function" ? existing(rule, context) : existing),
185
- copyCheckRule(rule, options)
241
+ copyCheckRule(rule, typeOptions)
186
242
  ];
187
243
  return { ...t, validation };
188
244
  });
189
245
  }
246
+ function withCopyGuard(action, options = {}) {
247
+ let lastDoc;
248
+ let lastBlocking = [];
249
+ const call = action;
250
+ const guarded = (props) => {
251
+ const result = call(props);
252
+ if (!result) return result;
253
+ const doc = props.draft ?? props.published;
254
+ if (doc !== lastDoc) {
255
+ lastDoc = doc;
256
+ lastBlocking = checkDocumentCopy(doc, { ...options, review: false }).filter((f) => f.tier === "block");
257
+ }
258
+ if (lastBlocking.length === 0) return result;
259
+ const more = lastBlocking.length > 1 ? ` (and ${lastBlocking.length - 1} more)` : "";
260
+ return { ...result, disabled: true, title: `${describeFinding(lastBlocking[0])}${more}` };
261
+ };
262
+ const tagged = guarded;
263
+ if (action.action !== void 0) tagged.action = action.action;
264
+ tagged.displayName = `withCopyGuard(${action.displayName ?? "action"})`;
265
+ return tagged;
266
+ }
190
267
  // Annotate the CommonJS export names for ESM import in node:
191
268
  0 && (module.exports = {
192
269
  DEFAULT_EXCLUDED_TYPES,
@@ -197,5 +274,6 @@ function withCopyCheck(types, options = {}) {
197
274
  describeFinding,
198
275
  documentClaims,
199
276
  pathToString,
200
- withCopyCheck
277
+ withCopyCheck,
278
+ withCopyGuard
201
279
  });
package/dist/index.d.cts CHANGED
@@ -40,6 +40,30 @@ interface CopyCheckOptions {
40
40
  * Studio shows every finding as a warning and blocks nothing either way.
41
41
  */
42
42
  review?: boolean;
43
+ /**
44
+ * Check only these languages, e.g. `["en"]`. The rules are English, so on
45
+ * a French field they are noise. `"en"` also matches `en-GB` and `en_US`.
46
+ * When set, copy is skipped when it sits:
47
+ *
48
+ * - in an array item whose `language` field is another language
49
+ * (sanity-plugin-internationalized-array v5), or whose `_key` is
50
+ * (v4 and earlier: an `internationalizedArray*` item, or one with a
51
+ * `value` field);
52
+ * - under an object key that is another language, in an object whose keys
53
+ * are all two-letter language tags (field-level translation, e.g.
54
+ * `{ en, fr }` or `{ en_GB, nb_NO }`);
55
+ * - in a document whose own `language` field is another language
56
+ * (@sanity/document-internationalization).
57
+ *
58
+ * Unset: every language is checked, as before.
59
+ */
60
+ languages?: string[];
61
+ /**
62
+ * Dot paths of fields an editor never sees (`hidden: true` in the schema),
63
+ * e.g. `["seo.internalNotes"]`. Never read. `withCopyCheck` fills this in
64
+ * from the schema; pass it yourself only when calling the check directly.
65
+ */
66
+ hiddenPaths?: string[];
43
67
  }
44
68
  declare const DEFAULT_EXCLUDED_TYPES: string[];
45
69
  declare const DEFAULT_SKIP_FIELDS: string[];
@@ -111,5 +135,42 @@ interface SchemaTypeLike {
111
135
  declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
112
136
  /** Every document type gains the copy check as a warning, beside the validation it already has. */
113
137
  declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
138
+ /** The part of a Studio document action's props this reads. */
139
+ interface DocumentActionPropsLike {
140
+ draft?: unknown;
141
+ published?: unknown;
142
+ }
143
+ /** The part of a document action's result this changes. */
144
+ interface DocumentActionResultLike {
145
+ disabled?: boolean;
146
+ title?: unknown;
147
+ }
148
+ /**
149
+ * A document action: a function from props to a description, with an
150
+ * optional `action` tag (`"publish"` on the built-in one). The props
151
+ * parameter is `never` so Sanity's own, narrower props type fits.
152
+ */
153
+ type DocumentActionLike = ((props: never) => DocumentActionResultLike | null | undefined) & {
154
+ action?: string;
155
+ displayName?: string;
156
+ };
157
+ /**
158
+ * Opt-in: the publish action, disabled while the document has a house-rule
159
+ * (blocking tier) finding. The review tier never blocks.
160
+ *
161
+ * document: {
162
+ * actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
163
+ * }
164
+ *
165
+ * The original action is always called first, with the same props, so any
166
+ * hooks it uses run in the same order on every render. Its result is
167
+ * returned as it is, except for `disabled` and the `title` tooltip naming
168
+ * the first finding. Everything else in the package warns and never blocks;
169
+ * this is the one place that can, and only where a Studio adds it.
170
+ *
171
+ * Returns the caller's own action type, so the Studio's `actions` array
172
+ * keeps its type.
173
+ */
174
+ declare function withCopyGuard<A extends DocumentActionLike>(action: A, options?: CopyCheckOptions): A;
114
175
 
115
- export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck };
176
+ export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentActionLike, type DocumentActionPropsLike, type DocumentActionResultLike, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck, withCopyGuard };
package/dist/index.d.ts CHANGED
@@ -40,6 +40,30 @@ interface CopyCheckOptions {
40
40
  * Studio shows every finding as a warning and blocks nothing either way.
41
41
  */
42
42
  review?: boolean;
43
+ /**
44
+ * Check only these languages, e.g. `["en"]`. The rules are English, so on
45
+ * a French field they are noise. `"en"` also matches `en-GB` and `en_US`.
46
+ * When set, copy is skipped when it sits:
47
+ *
48
+ * - in an array item whose `language` field is another language
49
+ * (sanity-plugin-internationalized-array v5), or whose `_key` is
50
+ * (v4 and earlier: an `internationalizedArray*` item, or one with a
51
+ * `value` field);
52
+ * - under an object key that is another language, in an object whose keys
53
+ * are all two-letter language tags (field-level translation, e.g.
54
+ * `{ en, fr }` or `{ en_GB, nb_NO }`);
55
+ * - in a document whose own `language` field is another language
56
+ * (@sanity/document-internationalization).
57
+ *
58
+ * Unset: every language is checked, as before.
59
+ */
60
+ languages?: string[];
61
+ /**
62
+ * Dot paths of fields an editor never sees (`hidden: true` in the schema),
63
+ * e.g. `["seo.internalNotes"]`. Never read. `withCopyCheck` fills this in
64
+ * from the schema; pass it yourself only when calling the check directly.
65
+ */
66
+ hiddenPaths?: string[];
43
67
  }
44
68
  declare const DEFAULT_EXCLUDED_TYPES: string[];
45
69
  declare const DEFAULT_SKIP_FIELDS: string[];
@@ -111,5 +135,42 @@ interface SchemaTypeLike {
111
135
  declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
112
136
  /** Every document type gains the copy check as a warning, beside the validation it already has. */
113
137
  declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
138
+ /** The part of a Studio document action's props this reads. */
139
+ interface DocumentActionPropsLike {
140
+ draft?: unknown;
141
+ published?: unknown;
142
+ }
143
+ /** The part of a document action's result this changes. */
144
+ interface DocumentActionResultLike {
145
+ disabled?: boolean;
146
+ title?: unknown;
147
+ }
148
+ /**
149
+ * A document action: a function from props to a description, with an
150
+ * optional `action` tag (`"publish"` on the built-in one). The props
151
+ * parameter is `never` so Sanity's own, narrower props type fits.
152
+ */
153
+ type DocumentActionLike = ((props: never) => DocumentActionResultLike | null | undefined) & {
154
+ action?: string;
155
+ displayName?: string;
156
+ };
157
+ /**
158
+ * Opt-in: the publish action, disabled while the document has a house-rule
159
+ * (blocking tier) finding. The review tier never blocks.
160
+ *
161
+ * document: {
162
+ * actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
163
+ * }
164
+ *
165
+ * The original action is always called first, with the same props, so any
166
+ * hooks it uses run in the same order on every render. Its result is
167
+ * returned as it is, except for `disabled` and the `title` tooltip naming
168
+ * the first finding. Everything else in the package warns and never blocks;
169
+ * this is the one place that can, and only where a Studio adds it.
170
+ *
171
+ * Returns the caller's own action type, so the Studio's `actions` array
172
+ * keeps its type.
173
+ */
174
+ declare function withCopyGuard<A extends DocumentActionLike>(action: A, options?: CopyCheckOptions): A;
114
175
 
115
- export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck };
176
+ export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentActionLike, type DocumentActionPropsLike, type DocumentActionResultLike, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck, withCopyGuard };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/core.ts
2
2
  import { applyHouseGate, checkCopy, findClaims } from "@domandigital/craft";
3
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
3
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
4
4
  var DEFAULT_SKIP_FIELDS = [
5
5
  "slug",
6
6
  "url",
@@ -24,17 +24,35 @@ var DEFAULT_SKIP_FIELDS = [
24
24
  "script",
25
25
  "schema",
26
26
  "jsonLd",
27
- "canonical"
27
+ "canonical",
28
+ "language",
29
+ "locale"
28
30
  ];
29
31
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
30
32
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
31
33
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
32
34
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
35
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
36
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
37
+ function languageWanted(tag, wanted) {
38
+ const t = tag.toLowerCase().replace(/_/g, "-");
39
+ return wanted.some((w) => {
40
+ const base = w.toLowerCase().replace(/_/g, "-");
41
+ return t === base || t.startsWith(`${base}-`);
42
+ });
43
+ }
44
+ function itemLanguage(item) {
45
+ if (typeof item.language === "string") return item.language;
46
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
47
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
48
+ return void 0;
49
+ }
33
50
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
34
51
  function notCopy(text) {
35
52
  const t = text.trim();
36
53
  if (!t) return true;
37
54
  if (/^[a-z0-9_-]+$/.test(t)) return true;
55
+ if (LANGUAGE_TAG.test(t)) return true;
38
56
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
39
57
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
40
58
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -53,7 +71,13 @@ function blockText(block) {
53
71
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
54
72
  function collectCopy(doc, options = {}) {
55
73
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
74
+ const hidden = new Set(options.hiddenPaths ?? []);
75
+ const languages = options.languages;
56
76
  const pieces = [];
77
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
78
+ return pieces;
79
+ }
80
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
57
81
  const walk = (value, path) => {
58
82
  if (typeof value === "string") {
59
83
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -61,6 +85,10 @@ function collectCopy(doc, options = {}) {
61
85
  }
62
86
  if (Array.isArray(value)) {
63
87
  value.forEach((item, i) => {
88
+ if (languages && isRecord(item)) {
89
+ const language = itemLanguage(item);
90
+ if (language && !languageWanted(language, languages)) return;
91
+ }
64
92
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
65
93
  const text = blockText(item);
66
94
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -73,9 +101,15 @@ function collectCopy(doc, options = {}) {
73
101
  if (!isRecord(value)) return;
74
102
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
75
103
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
104
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
105
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
76
106
  for (const [key, child] of Object.entries(value)) {
77
107
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
78
- walk(child, [...path, key]);
108
+ if (localeMap && !languageWanted(key, languages)) continue;
109
+ const childPath = [...path, key];
110
+ const dotted = fieldPath(childPath);
111
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
112
+ walk(child, childPath);
79
113
  }
80
114
  };
81
115
  walk(doc, []);
@@ -129,10 +163,11 @@ function pathToString(path) {
129
163
 
130
164
  // src/schema.ts
131
165
  function copyCheckRule(rule, options = {}) {
132
- let lastInput = "";
166
+ let lastInput;
133
167
  let lastResult = true;
134
168
  return rule.custom((doc) => {
135
- const input = JSON.stringify(doc ?? null);
169
+ const type = doc !== null && typeof doc === "object" ? doc._type : void 0;
170
+ const input = JSON.stringify([type, collectCopy(doc, options)]);
136
171
  if (input === lastInput) return lastResult;
137
172
  lastInput = input;
138
173
  const findings = checkDocumentCopy(doc, options);
@@ -140,19 +175,60 @@ function copyCheckRule(rule, options = {}) {
140
175
  return lastResult;
141
176
  }).warning();
142
177
  }
178
+ function staticHiddenPaths(type, byName, prefix = "", seen = /* @__PURE__ */ new Set()) {
179
+ const own = Array.isArray(type.fields) ? type.fields : void 0;
180
+ const named = typeof type.type === "string" ? byName.get(type.type) : void 0;
181
+ const fields = own ?? (named && Array.isArray(named.fields) ? named.fields : []);
182
+ if (!own && named && typeof type.type === "string") {
183
+ if (seen.has(type.type)) return [];
184
+ seen = new Set(seen).add(type.type);
185
+ }
186
+ const paths = [];
187
+ for (const field of fields) {
188
+ if (typeof field?.name !== "string") continue;
189
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
190
+ if (field.hidden === true) paths.push(path);
191
+ else paths.push(...staticHiddenPaths(field, byName, path, seen));
192
+ }
193
+ return paths;
194
+ }
143
195
  var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
144
196
  function withCopyCheck(types, options = {}) {
145
197
  const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
198
+ const byName = new Map(types.map((t) => [t.name, t]));
146
199
  return types.map((t) => {
147
200
  if (t.type !== "document" || excluded.has(t.name)) return t;
201
+ const hiddenPaths = [...options.hiddenPaths ?? [], ...staticHiddenPaths({ fields: t.fields }, byName)];
202
+ const typeOptions = hiddenPaths.length > 0 ? { ...options, hiddenPaths } : options;
148
203
  const existing = t.validation;
149
204
  const validation = (rule, context) => [
150
205
  ...asArray(typeof existing === "function" ? existing(rule, context) : existing),
151
- copyCheckRule(rule, options)
206
+ copyCheckRule(rule, typeOptions)
152
207
  ];
153
208
  return { ...t, validation };
154
209
  });
155
210
  }
211
+ function withCopyGuard(action, options = {}) {
212
+ let lastDoc;
213
+ let lastBlocking = [];
214
+ const call = action;
215
+ const guarded = (props) => {
216
+ const result = call(props);
217
+ if (!result) return result;
218
+ const doc = props.draft ?? props.published;
219
+ if (doc !== lastDoc) {
220
+ lastDoc = doc;
221
+ lastBlocking = checkDocumentCopy(doc, { ...options, review: false }).filter((f) => f.tier === "block");
222
+ }
223
+ if (lastBlocking.length === 0) return result;
224
+ const more = lastBlocking.length > 1 ? ` (and ${lastBlocking.length - 1} more)` : "";
225
+ return { ...result, disabled: true, title: `${describeFinding(lastBlocking[0])}${more}` };
226
+ };
227
+ const tagged = guarded;
228
+ if (action.action !== void 0) tagged.action = action.action;
229
+ tagged.displayName = `withCopyGuard(${action.displayName ?? "action"})`;
230
+ return tagged;
231
+ }
156
232
  export {
157
233
  DEFAULT_EXCLUDED_TYPES,
158
234
  DEFAULT_SKIP_FIELDS,
@@ -162,5 +238,6 @@ export {
162
238
  describeFinding,
163
239
  documentClaims,
164
240
  pathToString,
165
- withCopyCheck
241
+ withCopyCheck,
242
+ withCopyGuard
166
243
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/sanity-copy",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "description": "The Doman Digital house copy check in Sanity Studio: every document type gains craft's copy rules as validation warnings on the field that caused them. Also a pure checker for a document or an export. No Sanity dependency.",
6
6
  "license": "Apache-2.0",
@@ -8,10 +8,13 @@
8
8
  "main": "dist/index.cjs",
9
9
  "module": "dist/index.js",
10
10
  "types": "dist/index.d.ts",
11
+ "sideEffects": false,
11
12
  "exports": {
12
13
  ".": {
13
- "types": "./dist/index.d.ts",
14
- "import": "./dist/index.js",
14
+ "import": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
15
18
  "require": {
16
19
  "types": "./dist/index.d.cts",
17
20
  "default": "./dist/index.cjs"
@@ -31,7 +34,7 @@
31
34
  "vitest": "^2.1.9"
32
35
  },
33
36
  "engines": {
34
- "node": ">=20"
37
+ "node": ">=22.12"
35
38
  },
36
39
  "repository": {
37
40
  "type": "git",
@@ -47,7 +50,7 @@
47
50
  "provenance": true
48
51
  },
49
52
  "dependencies": {
50
- "@domandigital/craft": "^0.10.0"
53
+ "@domandigital/craft": "^0.11.0"
51
54
  },
52
55
  "keywords": [
53
56
  "sanity",