@domandigital/sanity-copy 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +202 -0
- package/README.md +76 -0
- package/dist/cli.js +218 -0
- package/dist/index.cjs +188 -0
- package/dist/index.d.cts +98 -0
- package/dist/index.d.ts +98 -0
- package/dist/index.js +154 -0
- package/package.json +67 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# @domandigital/sanity-copy
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 7765dda: First release. `withCopyCheck(schemaTypes)` adds the house copy check to every Sanity document type as validation warnings on the field that caused them, including inside Portable Text and image alt text. `checkDocumentCopy` runs the same check anywhere. The `sanity-copy` command sweeps a whole dataset (public, or private with `SANITY_API_TOKEN`) and lists findings by document and field. No Sanity dependency.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [2b6f823]
|
|
12
|
+
- Updated dependencies [7765dda]
|
|
13
|
+
- Updated dependencies [ef5b85b]
|
|
14
|
+
- @domandigital/craft@0.8.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Doman Digital Ltd
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# @domandigital/sanity-copy
|
|
2
|
+
|
|
3
|
+
The Doman Digital house copy check inside Sanity Studio. Every document type
|
|
4
|
+
gains craft's copy rules as validation **warnings**, on the exact field that
|
|
5
|
+
caused them, including inside Portable Text. Publishing always still works:
|
|
6
|
+
copy the owner types is advised on, never overridden.
|
|
7
|
+
|
|
8
|
+
The rules are `COPY.md` in [`@domandigital/craft`](../craft). This package
|
|
9
|
+
only decides which strings in a document are copy, and where each finding
|
|
10
|
+
belongs.
|
|
11
|
+
|
|
12
|
+
## In a Studio
|
|
13
|
+
|
|
14
|
+
Works in any Sanity Studio, v3 or later. Nothing in it is specific to one
|
|
15
|
+
site. Two steps:
|
|
16
|
+
|
|
17
|
+
1. `pnpm add @domandigital/sanity-copy` (or npm, or yarn) in the Studio's app.
|
|
18
|
+
2. Wrap the types array in `sanity.config.ts`, as below.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { defineConfig } from "sanity";
|
|
22
|
+
import { withCopyCheck } from "@domandigital/sanity-copy";
|
|
23
|
+
import { schemaTypes } from "./schemas";
|
|
24
|
+
|
|
25
|
+
export default defineConfig({
|
|
26
|
+
// ...
|
|
27
|
+
schema: { types: withCopyCheck(schemaTypes) },
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
An editor sees, on the field:
|
|
32
|
+
|
|
33
|
+
> House rule (Em dash): "local businesses — built". Use a full stop, a comma,
|
|
34
|
+
> or a colon.
|
|
35
|
+
|
|
36
|
+
Why a wrapper and not a plugin: a plugin's `schema.types` function runs before
|
|
37
|
+
the Studio's own types are added, so a plugin never sees them.
|
|
38
|
+
|
|
39
|
+
Options, all optional:
|
|
40
|
+
|
|
41
|
+
| Option | Default | What it does |
|
|
42
|
+
| --- | --- | --- |
|
|
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. |
|
|
45
|
+
| `review` | `true` | Show the review and density tiers as well as the house rules. |
|
|
46
|
+
|
|
47
|
+
What is read: strings, Portable Text (a block's spans joined, so a template
|
|
48
|
+
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.
|
|
50
|
+
|
|
51
|
+
## Sweeping a whole dataset
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npx @domandigital/sanity-copy --project <id> # a public dataset
|
|
55
|
+
SANITY_API_TOKEN=... npx @domandigital/sanity-copy --project <id> --types homepage,service
|
|
56
|
+
npx @domandigital/sanity-copy --file export.json --json
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Findings are listed per document and field. Exit **0** no house-rule finding,
|
|
60
|
+
**1** at least one, **2** nothing was checked. A token is read from the
|
|
61
|
+
environment, never a flag. It reports and changes nothing.
|
|
62
|
+
|
|
63
|
+
## In code
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { checkDocumentCopy, pathToString, describeFinding } from "@domandigital/sanity-copy";
|
|
67
|
+
|
|
68
|
+
for (const f of checkDocumentCopy(doc)) console.log(pathToString(f.path), describeFinding(f));
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
No Sanity dependency, and nothing a Studio imports touches Node, so the same
|
|
72
|
+
check runs in the Studio, a script and a test.
|
|
73
|
+
|
|
74
|
+
## Licence
|
|
75
|
+
|
|
76
|
+
Apache-2.0.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { readFileSync } from "fs";
|
|
5
|
+
|
|
6
|
+
// src/core.ts
|
|
7
|
+
import { applyHouseGate, checkCopy } from "@domandigital/craft";
|
|
8
|
+
var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
|
|
9
|
+
var DEFAULT_SKIP_FIELDS = [
|
|
10
|
+
"slug",
|
|
11
|
+
"url",
|
|
12
|
+
"href",
|
|
13
|
+
"link",
|
|
14
|
+
"email",
|
|
15
|
+
"phone",
|
|
16
|
+
"telephone",
|
|
17
|
+
"tel",
|
|
18
|
+
"icon",
|
|
19
|
+
"id",
|
|
20
|
+
"key",
|
|
21
|
+
"anchor",
|
|
22
|
+
"variant",
|
|
23
|
+
"theme",
|
|
24
|
+
"style",
|
|
25
|
+
"colour",
|
|
26
|
+
"color",
|
|
27
|
+
"code",
|
|
28
|
+
"embed",
|
|
29
|
+
"script",
|
|
30
|
+
"schema",
|
|
31
|
+
"jsonLd",
|
|
32
|
+
"canonical"
|
|
33
|
+
];
|
|
34
|
+
var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
|
|
35
|
+
var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
|
|
36
|
+
var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
|
|
37
|
+
var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
|
|
38
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
39
|
+
function notCopy(text) {
|
|
40
|
+
const t = text.trim();
|
|
41
|
+
if (!t) return true;
|
|
42
|
+
if (/^[a-z0-9_-]+$/.test(t)) return true;
|
|
43
|
+
if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
|
|
44
|
+
if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
|
|
45
|
+
if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
function blockText(block) {
|
|
49
|
+
const children = Array.isArray(block.children) ? block.children : [];
|
|
50
|
+
const text = children.map((c) => isRecord(c) && typeof c.text === "string" ? c.text : "").join("");
|
|
51
|
+
const style = typeof block.style === "string" ? block.style : "normal";
|
|
52
|
+
const heading = /^h([1-6])$/.exec(style);
|
|
53
|
+
if (heading) return `${"#".repeat(Number(heading[1]))} ${text}`;
|
|
54
|
+
if (block.listItem) return `${block.listItem === "number" ? "1." : "-"} ${text}`;
|
|
55
|
+
if (style === "blockquote") return `> ${text}`;
|
|
56
|
+
return text;
|
|
57
|
+
}
|
|
58
|
+
var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
|
|
59
|
+
function collectCopy(doc, options = {}) {
|
|
60
|
+
const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
|
|
61
|
+
const pieces = [];
|
|
62
|
+
const walk = (value, path) => {
|
|
63
|
+
if (typeof value === "string") {
|
|
64
|
+
if (!notCopy(value)) pieces.push({ path, text: value });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(value)) {
|
|
68
|
+
value.forEach((item, i) => {
|
|
69
|
+
if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
|
|
70
|
+
const text = blockText(item);
|
|
71
|
+
if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
|
|
72
|
+
} else {
|
|
73
|
+
walk(item, [...path, segment(item, i)]);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (!isRecord(value)) return;
|
|
79
|
+
if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
|
|
80
|
+
const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
|
|
81
|
+
for (const [key, child] of Object.entries(value)) {
|
|
82
|
+
if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
|
|
83
|
+
walk(child, [...path, key]);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
walk(doc, []);
|
|
87
|
+
return pieces;
|
|
88
|
+
}
|
|
89
|
+
var fileFor = (index) => `field-${index}.md`;
|
|
90
|
+
function checkDocumentCopy(doc, options = {}) {
|
|
91
|
+
if (!isRecord(doc)) return [];
|
|
92
|
+
const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
|
|
93
|
+
if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
|
|
94
|
+
const pieces = collectCopy(doc, options);
|
|
95
|
+
if (pieces.length === 0) return [];
|
|
96
|
+
const review = options.review ?? true;
|
|
97
|
+
const keep = (tier) => tier === "block" || review && tier === "review";
|
|
98
|
+
const findings = [];
|
|
99
|
+
const files = pieces.map((p, i) => ({ path: fileFor(i), text: p.text }));
|
|
100
|
+
const perField = applyHouseGate(checkCopy(files, {}));
|
|
101
|
+
for (const f of perField.findings) {
|
|
102
|
+
if (DENSITY_TELLS.includes(f.tell) || !keep(f.house)) continue;
|
|
103
|
+
const index = Number(/^field-(\d+)\.md$/.exec(f.path)?.[1]);
|
|
104
|
+
const piece = pieces[index];
|
|
105
|
+
if (!piece) continue;
|
|
106
|
+
findings.push({ path: piece.path, tell: f.tell, name: f.name, tier: f.house, message: f.message, fix: f.fix });
|
|
107
|
+
}
|
|
108
|
+
if (review) {
|
|
109
|
+
const whole = [{ path: "document.md", text: pieces.map((p) => p.text).join("\n\n") }];
|
|
110
|
+
for (const f of checkCopy(whole, { only: DENSITY_TELLS }).findings) {
|
|
111
|
+
findings.push({ path: [], tell: f.tell, name: f.name, tier: "review", message: f.message, fix: f.fix });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return findings;
|
|
115
|
+
}
|
|
116
|
+
function describeFinding(f) {
|
|
117
|
+
const lead = f.tier === "block" ? "House rule" : "Worth a look";
|
|
118
|
+
return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
|
|
119
|
+
}
|
|
120
|
+
function pathToString(path) {
|
|
121
|
+
return path.map((s, i) => typeof s === "string" ? `${i ? "." : ""}${s}` : typeof s === "number" ? `[${s}]` : `[_key=="${s._key}"]`).join("");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/cli.ts
|
|
125
|
+
function parse(argv) {
|
|
126
|
+
const args = { dataset: "production", json: false };
|
|
127
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
128
|
+
const a = argv[i];
|
|
129
|
+
const value = () => {
|
|
130
|
+
const v = argv[++i];
|
|
131
|
+
if (!v || v.startsWith("--")) throw new Error(`${a} needs a value`);
|
|
132
|
+
return v;
|
|
133
|
+
};
|
|
134
|
+
if (a === "--project") args.project = value();
|
|
135
|
+
else if (a === "--dataset") args.dataset = value();
|
|
136
|
+
else if (a === "--types") args.types = value().split(",").map((t) => t.trim()).filter(Boolean);
|
|
137
|
+
else if (a === "--file") args.file = value();
|
|
138
|
+
else if (a === "--json") args.json = true;
|
|
139
|
+
else if (a === "--help" || a === "-h") return "help";
|
|
140
|
+
else return `unknown option ${a}`;
|
|
141
|
+
}
|
|
142
|
+
if (!args.project && !args.file) return "give --project <id> or --file <export.json>";
|
|
143
|
+
return args;
|
|
144
|
+
}
|
|
145
|
+
async function fetchDocuments(args) {
|
|
146
|
+
if (args.file) {
|
|
147
|
+
const data = JSON.parse(readFileSync(args.file, "utf8"));
|
|
148
|
+
const list = Array.isArray(data) ? data : data.result;
|
|
149
|
+
if (!Array.isArray(list)) throw new Error(`${args.file} holds no array of documents`);
|
|
150
|
+
return list;
|
|
151
|
+
}
|
|
152
|
+
if (!/^[a-z0-9-]+$/i.test(args.project) || !/^[a-z0-9_-]+$/i.test(args.dataset)) throw new Error("project and dataset are letters, numbers and dashes only");
|
|
153
|
+
const typeFilter = args.types?.length ? " && _type in $types" : "";
|
|
154
|
+
const query = `*[!(_id in path("drafts.**")) && !(_type match "sanity.*")${typeFilter}]`;
|
|
155
|
+
const params = new URLSearchParams({ query });
|
|
156
|
+
if (args.types?.length) params.set("$types", JSON.stringify(args.types));
|
|
157
|
+
const token = process.env.SANITY_API_TOKEN ?? process.env.SANITY_AUTH_TOKEN;
|
|
158
|
+
const host = token ? "api.sanity.io" : "apicdn.sanity.io";
|
|
159
|
+
const res = await fetch(`https://${args.project}.${host}/v2025-02-19/data/query/${args.dataset}?${params}`, {
|
|
160
|
+
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
|
161
|
+
});
|
|
162
|
+
if (!res.ok) throw new Error(`Sanity answered ${res.status}${token ? "" : ": a private dataset needs SANITY_API_TOKEN"}`);
|
|
163
|
+
const body = await res.json();
|
|
164
|
+
if (!Array.isArray(body.result)) throw new Error("Sanity returned no documents");
|
|
165
|
+
return body.result;
|
|
166
|
+
}
|
|
167
|
+
var label = (doc) => {
|
|
168
|
+
const slug = doc.slug;
|
|
169
|
+
return `${doc._type}/${slug?.current ?? doc._id}`;
|
|
170
|
+
};
|
|
171
|
+
async function main(argv, out = console.log, err = console.error) {
|
|
172
|
+
const args = parse(argv);
|
|
173
|
+
if (args === "help") {
|
|
174
|
+
out("usage: sanity-copy --project <id> [--dataset production] [--types a,b] [--json]\n sanity-copy --file export.json [--json]");
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
if (typeof args === "string") {
|
|
178
|
+
err(`sanity-copy: ${args}`);
|
|
179
|
+
return 2;
|
|
180
|
+
}
|
|
181
|
+
let docs;
|
|
182
|
+
try {
|
|
183
|
+
docs = await fetchDocuments(args);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
err(`sanity-copy: ${e.message}. Nothing was checked.`);
|
|
186
|
+
return 2;
|
|
187
|
+
}
|
|
188
|
+
if (docs.length === 0) {
|
|
189
|
+
err("sanity-copy: the dataset returned 0 documents. Nothing was checked.");
|
|
190
|
+
return 2;
|
|
191
|
+
}
|
|
192
|
+
const results = [];
|
|
193
|
+
for (const doc of docs) {
|
|
194
|
+
const findings = checkDocumentCopy(doc);
|
|
195
|
+
if (findings.length) results.push({ doc: label(doc), findings });
|
|
196
|
+
}
|
|
197
|
+
const all = results.flatMap((r) => r.findings);
|
|
198
|
+
const block = all.filter((f) => f.tier === "block").length;
|
|
199
|
+
if (args.json) {
|
|
200
|
+
out(JSON.stringify({ documents: docs.length, block, review: all.length - block, results }, null, 2));
|
|
201
|
+
} else {
|
|
202
|
+
for (const r of results) {
|
|
203
|
+
out(r.doc);
|
|
204
|
+
for (const f of r.findings) out(` ${pathToString(f.path) || "(whole document)"} ${describeFinding(f)}`);
|
|
205
|
+
}
|
|
206
|
+
out(`
|
|
207
|
+
sanity-copy: ${docs.length} documents, ${block} house-rule finding${block === 1 ? "" : "s"}, ${all.length - block} worth a look.`);
|
|
208
|
+
out("Reports only: copy the owner typed is theirs to change.");
|
|
209
|
+
}
|
|
210
|
+
return block > 0 ? 1 : 0;
|
|
211
|
+
}
|
|
212
|
+
var invoked = process.argv[1] ?? "";
|
|
213
|
+
if (/sanity-copy|cli\.(?:c?js|ts)$/.test(invoked)) {
|
|
214
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
215
|
+
}
|
|
216
|
+
export {
|
|
217
|
+
main
|
|
218
|
+
};
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
DEFAULT_EXCLUDED_TYPES: () => DEFAULT_EXCLUDED_TYPES,
|
|
24
|
+
DEFAULT_SKIP_FIELDS: () => DEFAULT_SKIP_FIELDS,
|
|
25
|
+
checkDocumentCopy: () => checkDocumentCopy,
|
|
26
|
+
collectCopy: () => collectCopy,
|
|
27
|
+
copyCheckRule: () => copyCheckRule,
|
|
28
|
+
describeFinding: () => describeFinding,
|
|
29
|
+
pathToString: () => pathToString,
|
|
30
|
+
withCopyCheck: () => withCopyCheck
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(index_exports);
|
|
33
|
+
|
|
34
|
+
// src/core.ts
|
|
35
|
+
var import_craft = require("@domandigital/craft");
|
|
36
|
+
var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
|
|
37
|
+
var DEFAULT_SKIP_FIELDS = [
|
|
38
|
+
"slug",
|
|
39
|
+
"url",
|
|
40
|
+
"href",
|
|
41
|
+
"link",
|
|
42
|
+
"email",
|
|
43
|
+
"phone",
|
|
44
|
+
"telephone",
|
|
45
|
+
"tel",
|
|
46
|
+
"icon",
|
|
47
|
+
"id",
|
|
48
|
+
"key",
|
|
49
|
+
"anchor",
|
|
50
|
+
"variant",
|
|
51
|
+
"theme",
|
|
52
|
+
"style",
|
|
53
|
+
"colour",
|
|
54
|
+
"color",
|
|
55
|
+
"code",
|
|
56
|
+
"embed",
|
|
57
|
+
"script",
|
|
58
|
+
"schema",
|
|
59
|
+
"jsonLd",
|
|
60
|
+
"canonical"
|
|
61
|
+
];
|
|
62
|
+
var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
|
|
63
|
+
var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
|
|
64
|
+
var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
|
|
65
|
+
var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
|
|
66
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
67
|
+
function notCopy(text) {
|
|
68
|
+
const t = text.trim();
|
|
69
|
+
if (!t) return true;
|
|
70
|
+
if (/^[a-z0-9_-]+$/.test(t)) return true;
|
|
71
|
+
if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
|
|
72
|
+
if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
|
|
73
|
+
if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
function blockText(block) {
|
|
77
|
+
const children = Array.isArray(block.children) ? block.children : [];
|
|
78
|
+
const text = children.map((c) => isRecord(c) && typeof c.text === "string" ? c.text : "").join("");
|
|
79
|
+
const style = typeof block.style === "string" ? block.style : "normal";
|
|
80
|
+
const heading = /^h([1-6])$/.exec(style);
|
|
81
|
+
if (heading) return `${"#".repeat(Number(heading[1]))} ${text}`;
|
|
82
|
+
if (block.listItem) return `${block.listItem === "number" ? "1." : "-"} ${text}`;
|
|
83
|
+
if (style === "blockquote") return `> ${text}`;
|
|
84
|
+
return text;
|
|
85
|
+
}
|
|
86
|
+
var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
|
|
87
|
+
function collectCopy(doc, options = {}) {
|
|
88
|
+
const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
|
|
89
|
+
const pieces = [];
|
|
90
|
+
const walk = (value, path) => {
|
|
91
|
+
if (typeof value === "string") {
|
|
92
|
+
if (!notCopy(value)) pieces.push({ path, text: value });
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (Array.isArray(value)) {
|
|
96
|
+
value.forEach((item, i) => {
|
|
97
|
+
if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
|
|
98
|
+
const text = blockText(item);
|
|
99
|
+
if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
|
|
100
|
+
} else {
|
|
101
|
+
walk(item, [...path, segment(item, i)]);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (!isRecord(value)) return;
|
|
107
|
+
if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
|
|
108
|
+
const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
|
|
109
|
+
for (const [key, child] of Object.entries(value)) {
|
|
110
|
+
if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
|
|
111
|
+
walk(child, [...path, key]);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
walk(doc, []);
|
|
115
|
+
return pieces;
|
|
116
|
+
}
|
|
117
|
+
var fileFor = (index) => `field-${index}.md`;
|
|
118
|
+
function checkDocumentCopy(doc, options = {}) {
|
|
119
|
+
if (!isRecord(doc)) return [];
|
|
120
|
+
const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
|
|
121
|
+
if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
|
|
122
|
+
const pieces = collectCopy(doc, options);
|
|
123
|
+
if (pieces.length === 0) return [];
|
|
124
|
+
const review = options.review ?? true;
|
|
125
|
+
const keep = (tier) => tier === "block" || review && tier === "review";
|
|
126
|
+
const findings = [];
|
|
127
|
+
const files = pieces.map((p, i) => ({ path: fileFor(i), text: p.text }));
|
|
128
|
+
const perField = (0, import_craft.applyHouseGate)((0, import_craft.checkCopy)(files, {}));
|
|
129
|
+
for (const f of perField.findings) {
|
|
130
|
+
if (DENSITY_TELLS.includes(f.tell) || !keep(f.house)) continue;
|
|
131
|
+
const index = Number(/^field-(\d+)\.md$/.exec(f.path)?.[1]);
|
|
132
|
+
const piece = pieces[index];
|
|
133
|
+
if (!piece) continue;
|
|
134
|
+
findings.push({ path: piece.path, tell: f.tell, name: f.name, tier: f.house, message: f.message, fix: f.fix });
|
|
135
|
+
}
|
|
136
|
+
if (review) {
|
|
137
|
+
const whole = [{ path: "document.md", text: pieces.map((p) => p.text).join("\n\n") }];
|
|
138
|
+
for (const f of (0, import_craft.checkCopy)(whole, { only: DENSITY_TELLS }).findings) {
|
|
139
|
+
findings.push({ path: [], tell: f.tell, name: f.name, tier: "review", message: f.message, fix: f.fix });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return findings;
|
|
143
|
+
}
|
|
144
|
+
function describeFinding(f) {
|
|
145
|
+
const lead = f.tier === "block" ? "House rule" : "Worth a look";
|
|
146
|
+
return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
|
|
147
|
+
}
|
|
148
|
+
function pathToString(path) {
|
|
149
|
+
return path.map((s, i) => typeof s === "string" ? `${i ? "." : ""}${s}` : typeof s === "number" ? `[${s}]` : `[_key=="${s._key}"]`).join("");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/schema.ts
|
|
153
|
+
function copyCheckRule(rule, options = {}) {
|
|
154
|
+
let lastInput = "";
|
|
155
|
+
let lastResult = true;
|
|
156
|
+
return rule.custom((doc) => {
|
|
157
|
+
const input = JSON.stringify(doc ?? null);
|
|
158
|
+
if (input === lastInput) return lastResult;
|
|
159
|
+
lastInput = input;
|
|
160
|
+
const findings = checkDocumentCopy(doc, options);
|
|
161
|
+
lastResult = findings.length === 0 ? true : findings.map((f) => ({ message: describeFinding(f), path: f.path }));
|
|
162
|
+
return lastResult;
|
|
163
|
+
}).warning();
|
|
164
|
+
}
|
|
165
|
+
var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
|
|
166
|
+
function withCopyCheck(types, options = {}) {
|
|
167
|
+
const excluded = new Set(options.excludeTypes ?? ["testimonial", "review", "proofQuote", "quote"]);
|
|
168
|
+
return types.map((t) => {
|
|
169
|
+
if (t.type !== "document" || excluded.has(t.name)) return t;
|
|
170
|
+
const existing = t.validation;
|
|
171
|
+
const validation = (rule, context) => [
|
|
172
|
+
...asArray(typeof existing === "function" ? existing(rule, context) : existing),
|
|
173
|
+
copyCheckRule(rule, options)
|
|
174
|
+
];
|
|
175
|
+
return { ...t, validation };
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
179
|
+
0 && (module.exports = {
|
|
180
|
+
DEFAULT_EXCLUDED_TYPES,
|
|
181
|
+
DEFAULT_SKIP_FIELDS,
|
|
182
|
+
checkDocumentCopy,
|
|
183
|
+
collectCopy,
|
|
184
|
+
copyCheckRule,
|
|
185
|
+
describeFinding,
|
|
186
|
+
pathToString,
|
|
187
|
+
withCopyCheck
|
|
188
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The house copy check over a Sanity document.
|
|
3
|
+
*
|
|
4
|
+
* Pure: a document in, findings with Studio paths out. No Sanity import, so it
|
|
5
|
+
* runs in the Studio, in a Node script over an export, and in a test, and gives
|
|
6
|
+
* the same answer in all three. The rules are craft's: this file only decides
|
|
7
|
+
* which strings in a document are copy, and where each finding belongs.
|
|
8
|
+
*/
|
|
9
|
+
/** A Studio path: field names, array indices, or `{ _key }` for keyed array items. */
|
|
10
|
+
type PathSegment = string | number | {
|
|
11
|
+
_key: string;
|
|
12
|
+
};
|
|
13
|
+
type Path = PathSegment[];
|
|
14
|
+
type Tier = "block" | "review" | "explicit";
|
|
15
|
+
interface CopyFinding {
|
|
16
|
+
/** Where it is: the field, the array item, the Portable Text block. `[]` is the document. */
|
|
17
|
+
path: Path;
|
|
18
|
+
tell: string;
|
|
19
|
+
name: string;
|
|
20
|
+
tier: Tier;
|
|
21
|
+
/** What was found, as craft reports it. */
|
|
22
|
+
message: string;
|
|
23
|
+
/** What to do instead. */
|
|
24
|
+
fix: string;
|
|
25
|
+
}
|
|
26
|
+
interface CopyCheckOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Document types never checked. A person's own words (reviews,
|
|
29
|
+
* testimonials, quotes) are exempt from every house rule: editing them to
|
|
30
|
+
* pass a check falsifies a quotation.
|
|
31
|
+
*/
|
|
32
|
+
excludeTypes?: string[];
|
|
33
|
+
/** Field names never read, at any depth. Slugs, links, keys and ids are not copy. */
|
|
34
|
+
skipFields?: string[];
|
|
35
|
+
/**
|
|
36
|
+
* Report the review tier as well as the blocking tier. On by default: the
|
|
37
|
+
* Studio shows every finding as a warning and blocks nothing either way.
|
|
38
|
+
*/
|
|
39
|
+
review?: boolean;
|
|
40
|
+
}
|
|
41
|
+
declare const DEFAULT_EXCLUDED_TYPES: string[];
|
|
42
|
+
declare const DEFAULT_SKIP_FIELDS: string[];
|
|
43
|
+
interface Piece {
|
|
44
|
+
path: Path;
|
|
45
|
+
text: string;
|
|
46
|
+
}
|
|
47
|
+
/** Every piece of copy in a document, with the path an editor would click. */
|
|
48
|
+
declare function collectCopy(doc: unknown, options?: CopyCheckOptions): Piece[];
|
|
49
|
+
/** Check one document. Returns nothing for an excluded type. */
|
|
50
|
+
declare function checkDocumentCopy(doc: unknown, options?: CopyCheckOptions): CopyFinding[];
|
|
51
|
+
/** One line an editor can act on. */
|
|
52
|
+
declare function describeFinding(f: CopyFinding): string;
|
|
53
|
+
/** A path as text, for a report: `hero.title`, `body[_key=="a1"]`. */
|
|
54
|
+
declare function pathToString(path: Path): string;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The house copy check in Sanity Studio, as validation warnings.
|
|
58
|
+
*
|
|
59
|
+
* import { withCopyCheck } from "@domandigital/sanity-copy";
|
|
60
|
+
* export default defineConfig({ schema: { types: withCopyCheck(schemaTypes) } });
|
|
61
|
+
*
|
|
62
|
+
* Why a wrapper and not a plugin: a plugin's `schema.types` function runs
|
|
63
|
+
* before the Studio's own types are added, so it never sees them. Wrapping the
|
|
64
|
+
* array the Studio passes in is explicit and always sees every type.
|
|
65
|
+
*
|
|
66
|
+
* Warnings, never errors. Copy the owner types is advised on, never
|
|
67
|
+
* overridden: a warning shows the editor what the check found, on the field
|
|
68
|
+
* that caused it, and publishing still works.
|
|
69
|
+
*
|
|
70
|
+
* No Sanity import. The shapes below are the parts of Sanity's schema and
|
|
71
|
+
* rule API this uses, so the package works across Studio versions without a
|
|
72
|
+
* peer dependency to keep in step.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/** The part of Sanity's `Rule` this uses. Each call returns a new rule. */
|
|
76
|
+
interface RuleLike {
|
|
77
|
+
custom(fn: (value: unknown) => true | {
|
|
78
|
+
message: string;
|
|
79
|
+
path: Path;
|
|
80
|
+
}[]): RuleLike;
|
|
81
|
+
warning(message?: string): RuleLike;
|
|
82
|
+
}
|
|
83
|
+
/** The part of a Sanity schema type definition this reads. */
|
|
84
|
+
interface SchemaTypeLike {
|
|
85
|
+
name: string;
|
|
86
|
+
type: string;
|
|
87
|
+
validation?: unknown;
|
|
88
|
+
[key: string]: unknown;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The custom rule, on its own, for a Studio that composes validation itself:
|
|
92
|
+
* `validation: (rule) => [copyCheckRule(rule), ...]`.
|
|
93
|
+
*/
|
|
94
|
+
declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
|
|
95
|
+
/** Every document type gains the copy check as a warning, beside the validation it already has. */
|
|
96
|
+
declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
|
|
97
|
+
|
|
98
|
+
export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, pathToString, withCopyCheck };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The house copy check over a Sanity document.
|
|
3
|
+
*
|
|
4
|
+
* Pure: a document in, findings with Studio paths out. No Sanity import, so it
|
|
5
|
+
* runs in the Studio, in a Node script over an export, and in a test, and gives
|
|
6
|
+
* the same answer in all three. The rules are craft's: this file only decides
|
|
7
|
+
* which strings in a document are copy, and where each finding belongs.
|
|
8
|
+
*/
|
|
9
|
+
/** A Studio path: field names, array indices, or `{ _key }` for keyed array items. */
|
|
10
|
+
type PathSegment = string | number | {
|
|
11
|
+
_key: string;
|
|
12
|
+
};
|
|
13
|
+
type Path = PathSegment[];
|
|
14
|
+
type Tier = "block" | "review" | "explicit";
|
|
15
|
+
interface CopyFinding {
|
|
16
|
+
/** Where it is: the field, the array item, the Portable Text block. `[]` is the document. */
|
|
17
|
+
path: Path;
|
|
18
|
+
tell: string;
|
|
19
|
+
name: string;
|
|
20
|
+
tier: Tier;
|
|
21
|
+
/** What was found, as craft reports it. */
|
|
22
|
+
message: string;
|
|
23
|
+
/** What to do instead. */
|
|
24
|
+
fix: string;
|
|
25
|
+
}
|
|
26
|
+
interface CopyCheckOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Document types never checked. A person's own words (reviews,
|
|
29
|
+
* testimonials, quotes) are exempt from every house rule: editing them to
|
|
30
|
+
* pass a check falsifies a quotation.
|
|
31
|
+
*/
|
|
32
|
+
excludeTypes?: string[];
|
|
33
|
+
/** Field names never read, at any depth. Slugs, links, keys and ids are not copy. */
|
|
34
|
+
skipFields?: string[];
|
|
35
|
+
/**
|
|
36
|
+
* Report the review tier as well as the blocking tier. On by default: the
|
|
37
|
+
* Studio shows every finding as a warning and blocks nothing either way.
|
|
38
|
+
*/
|
|
39
|
+
review?: boolean;
|
|
40
|
+
}
|
|
41
|
+
declare const DEFAULT_EXCLUDED_TYPES: string[];
|
|
42
|
+
declare const DEFAULT_SKIP_FIELDS: string[];
|
|
43
|
+
interface Piece {
|
|
44
|
+
path: Path;
|
|
45
|
+
text: string;
|
|
46
|
+
}
|
|
47
|
+
/** Every piece of copy in a document, with the path an editor would click. */
|
|
48
|
+
declare function collectCopy(doc: unknown, options?: CopyCheckOptions): Piece[];
|
|
49
|
+
/** Check one document. Returns nothing for an excluded type. */
|
|
50
|
+
declare function checkDocumentCopy(doc: unknown, options?: CopyCheckOptions): CopyFinding[];
|
|
51
|
+
/** One line an editor can act on. */
|
|
52
|
+
declare function describeFinding(f: CopyFinding): string;
|
|
53
|
+
/** A path as text, for a report: `hero.title`, `body[_key=="a1"]`. */
|
|
54
|
+
declare function pathToString(path: Path): string;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The house copy check in Sanity Studio, as validation warnings.
|
|
58
|
+
*
|
|
59
|
+
* import { withCopyCheck } from "@domandigital/sanity-copy";
|
|
60
|
+
* export default defineConfig({ schema: { types: withCopyCheck(schemaTypes) } });
|
|
61
|
+
*
|
|
62
|
+
* Why a wrapper and not a plugin: a plugin's `schema.types` function runs
|
|
63
|
+
* before the Studio's own types are added, so it never sees them. Wrapping the
|
|
64
|
+
* array the Studio passes in is explicit and always sees every type.
|
|
65
|
+
*
|
|
66
|
+
* Warnings, never errors. Copy the owner types is advised on, never
|
|
67
|
+
* overridden: a warning shows the editor what the check found, on the field
|
|
68
|
+
* that caused it, and publishing still works.
|
|
69
|
+
*
|
|
70
|
+
* No Sanity import. The shapes below are the parts of Sanity's schema and
|
|
71
|
+
* rule API this uses, so the package works across Studio versions without a
|
|
72
|
+
* peer dependency to keep in step.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/** The part of Sanity's `Rule` this uses. Each call returns a new rule. */
|
|
76
|
+
interface RuleLike {
|
|
77
|
+
custom(fn: (value: unknown) => true | {
|
|
78
|
+
message: string;
|
|
79
|
+
path: Path;
|
|
80
|
+
}[]): RuleLike;
|
|
81
|
+
warning(message?: string): RuleLike;
|
|
82
|
+
}
|
|
83
|
+
/** The part of a Sanity schema type definition this reads. */
|
|
84
|
+
interface SchemaTypeLike {
|
|
85
|
+
name: string;
|
|
86
|
+
type: string;
|
|
87
|
+
validation?: unknown;
|
|
88
|
+
[key: string]: unknown;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The custom rule, on its own, for a Studio that composes validation itself:
|
|
92
|
+
* `validation: (rule) => [copyCheckRule(rule), ...]`.
|
|
93
|
+
*/
|
|
94
|
+
declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
|
|
95
|
+
/** Every document type gains the copy check as a warning, beside the validation it already has. */
|
|
96
|
+
declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
|
|
97
|
+
|
|
98
|
+
export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, pathToString, withCopyCheck };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// src/core.ts
|
|
2
|
+
import { applyHouseGate, checkCopy } from "@domandigital/craft";
|
|
3
|
+
var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
|
|
4
|
+
var DEFAULT_SKIP_FIELDS = [
|
|
5
|
+
"slug",
|
|
6
|
+
"url",
|
|
7
|
+
"href",
|
|
8
|
+
"link",
|
|
9
|
+
"email",
|
|
10
|
+
"phone",
|
|
11
|
+
"telephone",
|
|
12
|
+
"tel",
|
|
13
|
+
"icon",
|
|
14
|
+
"id",
|
|
15
|
+
"key",
|
|
16
|
+
"anchor",
|
|
17
|
+
"variant",
|
|
18
|
+
"theme",
|
|
19
|
+
"style",
|
|
20
|
+
"colour",
|
|
21
|
+
"color",
|
|
22
|
+
"code",
|
|
23
|
+
"embed",
|
|
24
|
+
"script",
|
|
25
|
+
"schema",
|
|
26
|
+
"jsonLd",
|
|
27
|
+
"canonical"
|
|
28
|
+
];
|
|
29
|
+
var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
|
|
30
|
+
var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
|
|
31
|
+
var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
|
|
32
|
+
var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
|
|
33
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
34
|
+
function notCopy(text) {
|
|
35
|
+
const t = text.trim();
|
|
36
|
+
if (!t) return true;
|
|
37
|
+
if (/^[a-z0-9_-]+$/.test(t)) return true;
|
|
38
|
+
if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
|
|
39
|
+
if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
|
|
40
|
+
if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
function blockText(block) {
|
|
44
|
+
const children = Array.isArray(block.children) ? block.children : [];
|
|
45
|
+
const text = children.map((c) => isRecord(c) && typeof c.text === "string" ? c.text : "").join("");
|
|
46
|
+
const style = typeof block.style === "string" ? block.style : "normal";
|
|
47
|
+
const heading = /^h([1-6])$/.exec(style);
|
|
48
|
+
if (heading) return `${"#".repeat(Number(heading[1]))} ${text}`;
|
|
49
|
+
if (block.listItem) return `${block.listItem === "number" ? "1." : "-"} ${text}`;
|
|
50
|
+
if (style === "blockquote") return `> ${text}`;
|
|
51
|
+
return text;
|
|
52
|
+
}
|
|
53
|
+
var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
|
|
54
|
+
function collectCopy(doc, options = {}) {
|
|
55
|
+
const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
|
|
56
|
+
const pieces = [];
|
|
57
|
+
const walk = (value, path) => {
|
|
58
|
+
if (typeof value === "string") {
|
|
59
|
+
if (!notCopy(value)) pieces.push({ path, text: value });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (Array.isArray(value)) {
|
|
63
|
+
value.forEach((item, i) => {
|
|
64
|
+
if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
|
|
65
|
+
const text = blockText(item);
|
|
66
|
+
if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
|
|
67
|
+
} else {
|
|
68
|
+
walk(item, [...path, segment(item, i)]);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (!isRecord(value)) return;
|
|
74
|
+
if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
|
|
75
|
+
const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
|
|
76
|
+
for (const [key, child] of Object.entries(value)) {
|
|
77
|
+
if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
|
|
78
|
+
walk(child, [...path, key]);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
walk(doc, []);
|
|
82
|
+
return pieces;
|
|
83
|
+
}
|
|
84
|
+
var fileFor = (index) => `field-${index}.md`;
|
|
85
|
+
function checkDocumentCopy(doc, options = {}) {
|
|
86
|
+
if (!isRecord(doc)) return [];
|
|
87
|
+
const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
|
|
88
|
+
if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
|
|
89
|
+
const pieces = collectCopy(doc, options);
|
|
90
|
+
if (pieces.length === 0) return [];
|
|
91
|
+
const review = options.review ?? true;
|
|
92
|
+
const keep = (tier) => tier === "block" || review && tier === "review";
|
|
93
|
+
const findings = [];
|
|
94
|
+
const files = pieces.map((p, i) => ({ path: fileFor(i), text: p.text }));
|
|
95
|
+
const perField = applyHouseGate(checkCopy(files, {}));
|
|
96
|
+
for (const f of perField.findings) {
|
|
97
|
+
if (DENSITY_TELLS.includes(f.tell) || !keep(f.house)) continue;
|
|
98
|
+
const index = Number(/^field-(\d+)\.md$/.exec(f.path)?.[1]);
|
|
99
|
+
const piece = pieces[index];
|
|
100
|
+
if (!piece) continue;
|
|
101
|
+
findings.push({ path: piece.path, tell: f.tell, name: f.name, tier: f.house, message: f.message, fix: f.fix });
|
|
102
|
+
}
|
|
103
|
+
if (review) {
|
|
104
|
+
const whole = [{ path: "document.md", text: pieces.map((p) => p.text).join("\n\n") }];
|
|
105
|
+
for (const f of checkCopy(whole, { only: DENSITY_TELLS }).findings) {
|
|
106
|
+
findings.push({ path: [], tell: f.tell, name: f.name, tier: "review", message: f.message, fix: f.fix });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return findings;
|
|
110
|
+
}
|
|
111
|
+
function describeFinding(f) {
|
|
112
|
+
const lead = f.tier === "block" ? "House rule" : "Worth a look";
|
|
113
|
+
return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
|
|
114
|
+
}
|
|
115
|
+
function pathToString(path) {
|
|
116
|
+
return path.map((s, i) => typeof s === "string" ? `${i ? "." : ""}${s}` : typeof s === "number" ? `[${s}]` : `[_key=="${s._key}"]`).join("");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/schema.ts
|
|
120
|
+
function copyCheckRule(rule, options = {}) {
|
|
121
|
+
let lastInput = "";
|
|
122
|
+
let lastResult = true;
|
|
123
|
+
return rule.custom((doc) => {
|
|
124
|
+
const input = JSON.stringify(doc ?? null);
|
|
125
|
+
if (input === lastInput) return lastResult;
|
|
126
|
+
lastInput = input;
|
|
127
|
+
const findings = checkDocumentCopy(doc, options);
|
|
128
|
+
lastResult = findings.length === 0 ? true : findings.map((f) => ({ message: describeFinding(f), path: f.path }));
|
|
129
|
+
return lastResult;
|
|
130
|
+
}).warning();
|
|
131
|
+
}
|
|
132
|
+
var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
|
|
133
|
+
function withCopyCheck(types, options = {}) {
|
|
134
|
+
const excluded = new Set(options.excludeTypes ?? ["testimonial", "review", "proofQuote", "quote"]);
|
|
135
|
+
return types.map((t) => {
|
|
136
|
+
if (t.type !== "document" || excluded.has(t.name)) return t;
|
|
137
|
+
const existing = t.validation;
|
|
138
|
+
const validation = (rule, context) => [
|
|
139
|
+
...asArray(typeof existing === "function" ? existing(rule, context) : existing),
|
|
140
|
+
copyCheckRule(rule, options)
|
|
141
|
+
];
|
|
142
|
+
return { ...t, validation };
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
export {
|
|
146
|
+
DEFAULT_EXCLUDED_TYPES,
|
|
147
|
+
DEFAULT_SKIP_FIELDS,
|
|
148
|
+
checkDocumentCopy,
|
|
149
|
+
collectCopy,
|
|
150
|
+
copyCheckRule,
|
|
151
|
+
describeFinding,
|
|
152
|
+
pathToString,
|
|
153
|
+
withCopyCheck
|
|
154
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@domandigital/sanity-copy",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"private": false,
|
|
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
|
+
"license": "Apache-2.0",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "dist/index.cjs",
|
|
9
|
+
"module": "dist/index.js",
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.cts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"CHANGELOG.md",
|
|
24
|
+
"LICENSE",
|
|
25
|
+
"README.md",
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"tsup": "^8.3.5",
|
|
30
|
+
"typescript": "^5.6.3",
|
|
31
|
+
"vitest": "^2.1.9"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=20"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/Doman-Digital/dd-packages.git",
|
|
39
|
+
"directory": "packages/sanity-copy"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/Doman-Digital/dd-packages/tree/main/packages/sanity-copy#readme",
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/Doman-Digital/dd-packages/issues"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public",
|
|
47
|
+
"provenance": true
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@domandigital/craft": "^0.8.0"
|
|
51
|
+
},
|
|
52
|
+
"keywords": [
|
|
53
|
+
"sanity",
|
|
54
|
+
"sanity-plugin",
|
|
55
|
+
"copy",
|
|
56
|
+
"linter",
|
|
57
|
+
"ai-writing"
|
|
58
|
+
],
|
|
59
|
+
"bin": {
|
|
60
|
+
"sanity-copy": "dist/cli.js"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsup",
|
|
64
|
+
"typecheck": "tsc --noEmit",
|
|
65
|
+
"test": "vitest run"
|
|
66
|
+
}
|
|
67
|
+
}
|