@buffcore/cli 0.8.47 → 0.8.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/commands/build/server-text.en.d.ts +5 -0
  3. package/dist/commands/build/server-text.en.js +5 -0
  4. package/dist/commands/build/server-text.js +5 -0
  5. package/dist/commands/build/server.d.ts +4 -0
  6. package/dist/commands/build/server.js +10 -1
  7. package/dist/commands/change-merge-serial.d.ts +6 -2
  8. package/dist/commands/change-merge-serial.js +5 -1
  9. package/dist/commands/change-merge.d.ts +2 -2
  10. package/dist/commands/change.js +3 -0
  11. package/dist/commands/check-skills.d.ts +16 -0
  12. package/dist/commands/check-skills.en.d.ts +14 -0
  13. package/dist/commands/check-skills.en.js +14 -0
  14. package/dist/commands/check-skills.es.d.ts +2 -0
  15. package/dist/commands/check-skills.es.js +14 -0
  16. package/dist/commands/check-skills.js +146 -0
  17. package/dist/commands/check.js +5 -0
  18. package/dist/commands/dev.d.ts +9 -2
  19. package/dist/commands/dev.js +24 -5
  20. package/dist/commands/extension/config-text.d.ts +2 -0
  21. package/dist/commands/extension/config-text.js +2 -0
  22. package/dist/commands/extension/index.js +14 -2
  23. package/dist/commands/extension/new.d.ts +16 -0
  24. package/dist/commands/extension/new.js +52 -0
  25. package/dist/commands/extension/pack-files.d.ts +23 -0
  26. package/dist/commands/extension/pack-files.js +78 -0
  27. package/dist/commands/extension/pack-scan.d.ts +24 -0
  28. package/dist/commands/extension/pack-scan.js +131 -0
  29. package/dist/commands/extension/pack.d.ts +48 -0
  30. package/dist/commands/extension/pack.js +142 -0
  31. package/dist/commands/extension/share-text.d.ts +3 -0
  32. package/dist/commands/extension/share-text.js +6 -0
  33. package/dist/commands/extension/share.en.d.ts +32 -0
  34. package/dist/commands/extension/share.en.js +32 -0
  35. package/dist/commands/extension/share.es.d.ts +2 -0
  36. package/dist/commands/extension/share.es.js +32 -0
  37. package/dist/commands/hardening.d.ts +3 -0
  38. package/dist/commands/hardening.en.d.ts +3 -0
  39. package/dist/commands/hardening.en.js +3 -0
  40. package/dist/commands/hardening.es.d.ts +2 -0
  41. package/dist/commands/hardening.es.js +3 -0
  42. package/dist/commands/hardening.js +19 -0
  43. package/dist/commands/prototype/comp-record.d.ts +5 -0
  44. package/dist/commands/prototype/comp-record.js +22 -0
  45. package/dist/commands/server/build.d.ts +2 -1
  46. package/dist/commands/server/build.js +10 -2
  47. package/dist/commands/server/deploy-local.d.ts +3 -0
  48. package/dist/commands/server/deploy-local.js +9 -0
  49. package/dist/commands/server/deploy-plan.d.ts +5 -0
  50. package/dist/commands/server/deploy-plan.js +56 -0
  51. package/dist/commands/server/deploy-result.d.ts +7 -0
  52. package/dist/commands/server/deploy-result.js +1 -0
  53. package/dist/commands/server/deploy-script.d.ts +2 -0
  54. package/dist/commands/server/deploy-script.js +3 -2
  55. package/dist/commands/server/deploy.d.ts +9 -6
  56. package/dist/commands/server/deploy.js +39 -61
  57. package/dist/commands/server/files.d.ts +9 -1
  58. package/dist/commands/server/files.js +25 -5
  59. package/dist/commands/server/image.d.ts +4 -2
  60. package/dist/commands/server/image.js +6 -5
  61. package/dist/commands/server/setup.d.ts +1 -0
  62. package/dist/commands/server/setup.js +4 -0
  63. package/dist/commands/server/system-packages.d.ts +29 -0
  64. package/dist/commands/server/system-packages.js +103 -0
  65. package/dist/commands/services/compose.d.ts +1 -1
  66. package/dist/commands/services/compose.js +5 -3
  67. package/dist/commands/ui/agents-route.js +2 -0
  68. package/dist/commands/ui/approval-authority.en.d.ts +1 -0
  69. package/dist/commands/ui/approval-authority.en.js +1 -0
  70. package/dist/commands/ui/approval-authority.es.d.ts +1 -0
  71. package/dist/commands/ui/approval-authority.es.js +1 -0
  72. package/dist/commands/ui/approval-authority.js +7 -2
  73. package/dist/commands/ui/approve.js +2 -4
  74. package/dist/commands/ui/autopilot-records.d.ts +2 -0
  75. package/dist/commands/ui/autopilot-records.js +5 -0
  76. package/dist/commands/ui/brand-approval.js +5 -1
  77. package/dist/commands/ui/chat/permissions.js +1 -1
  78. package/dist/commands/ui/chat/routes.js +4 -0
  79. package/dist/commands/ui/comp-approval.d.ts +14 -2
  80. package/dist/commands/ui/comp-approval.js +45 -8
  81. package/dist/commands/ui/index.d.ts +1 -0
  82. package/dist/commands/ui/level-route.js +3 -0
  83. package/dist/commands/ui/merge-authority.d.ts +4 -1
  84. package/dist/commands/ui/merge-authority.en.d.ts +4 -0
  85. package/dist/commands/ui/merge-authority.en.js +5 -1
  86. package/dist/commands/ui/merge-authority.es.d.ts +4 -0
  87. package/dist/commands/ui/merge-authority.es.js +5 -1
  88. package/dist/commands/ui/merge-authority.js +6 -3
  89. package/dist/commands/ui/merge-claims.d.ts +7 -0
  90. package/dist/commands/ui/merge-claims.js +21 -0
  91. package/dist/commands/ui/merge-delegation.js +8 -3
  92. package/dist/commands/ui/merge-hold-name.d.ts +5 -0
  93. package/dist/commands/ui/merge-hold-name.js +5 -0
  94. package/dist/commands/ui/merge-hold.d.ts +6 -1
  95. package/dist/commands/ui/merge-hold.js +23 -5
  96. package/dist/commands/ui/merge-publish-host.d.ts +1 -0
  97. package/dist/commands/ui/merge-publish-host.js +2 -2
  98. package/dist/commands/ui/merge-record.d.ts +2 -0
  99. package/dist/commands/ui/merge-record.js +1 -1
  100. package/dist/commands/ui/merge-route.js +17 -1
  101. package/dist/commands/ui/merge-settle.d.ts +32 -0
  102. package/dist/commands/ui/merge-settle.js +133 -0
  103. package/dist/commands/ui/merge-state.d.ts +5 -0
  104. package/dist/commands/ui/merge-state.js +7 -1
  105. package/dist/commands/ui/merge-withdraw.d.ts +9 -0
  106. package/dist/commands/ui/merge-withdraw.js +29 -0
  107. package/dist/commands/ui/outside-merge.d.ts +13 -0
  108. package/dist/commands/ui/outside-merge.js +84 -0
  109. package/dist/commands/ui/outside.d.ts +7 -4
  110. package/dist/commands/ui/outside.js +3 -0
  111. package/dist/commands/ui/plan-extensions.d.ts +34 -0
  112. package/dist/commands/ui/plan-extensions.en.d.ts +4 -0
  113. package/dist/commands/ui/plan-extensions.en.js +4 -0
  114. package/dist/commands/ui/plan-extensions.es.d.ts +2 -0
  115. package/dist/commands/ui/plan-extensions.es.js +4 -0
  116. package/dist/commands/ui/plan-extensions.js +86 -0
  117. package/dist/commands/ui/plan-files.js +9 -3
  118. package/dist/commands/ui/plan-structure.js +5 -7
  119. package/dist/commands/ui/prototype-comp-route.d.ts +12 -3
  120. package/dist/commands/ui/prototype-comp-route.js +35 -17
  121. package/dist/commands/ui/prototype-main.d.ts +6 -0
  122. package/dist/commands/ui/real-file.d.ts +11 -0
  123. package/dist/commands/ui/real-file.js +84 -0
  124. package/dist/commands/ui/save-route.js +4 -1
  125. package/dist/commands/ui/server.d.ts +1 -0
  126. package/dist/commands/ui/server.js +1 -0
  127. package/dist/commands/ui/studio-routes.js +2 -0
  128. package/dist/commands/ui/studio-state.d.ts +8 -0
  129. package/dist/commands/ui/studio-versions.js +19 -3
  130. package/dist/commands/ui/studio.en.d.ts +2 -0
  131. package/dist/commands/ui/studio.en.js +2 -0
  132. package/dist/commands/ui/studio.es.d.ts +2 -0
  133. package/dist/commands/ui/studio.es.js +2 -0
  134. package/dist/commands/upgrade.js +1 -1
  135. package/dist/ui/page.js +91 -91
  136. package/docs/EXTENSIONS.md +6 -0
  137. package/docs/PROTOTYPE.md +13 -0
  138. package/docs/WORKBENCH.md +55 -2
  139. package/package.json +11 -11
  140. package/skills/ape-add-ai-purpose/SKILL.md +1 -1
  141. package/skills/ape-add-event/SKILL.md +1 -1
  142. package/skills/ape-add-extension/SKILL.md +5 -1
  143. package/skills/ape-add-feature/SKILL.md +1 -1
  144. package/skills/ape-add-generator/SKILL.md +1 -1
  145. package/skills/ape-add-module/SKILL.md +1 -1
  146. package/skills/ape-add-route/SKILL.md +3 -1
  147. package/skills/ape-add-service/SKILL.md +1 -1
  148. package/skills/ape-add-translations/SKILL.md +2 -2
  149. package/skills/ape-admin-screen/SKILL.md +1 -1
  150. package/skills/ape-app-screen/SKILL.md +1 -1
  151. package/skills/ape-critique/SKILL.md +11 -32
  152. package/skills/ape-critique/references/after.md +15 -0
  153. package/skills/ape-critique/references/spacing-pass.md +20 -0
  154. package/skills/ape-deploy/SKILL.md +8 -3
  155. package/skills/ape-design-system/SKILL.md +15 -15
  156. package/skills/ape-design-system/references/by-hand.md +7 -0
  157. package/skills/ape-design-system/references/reference-study.md +11 -0
  158. package/skills/ape-diagnose/SKILL.md +24 -0
  159. package/skills/ape-migration/SKILL.md +1 -1
  160. package/skills/ape-plan-change/SKILL.md +37 -31
  161. package/skills/ape-plan-change/references/change-file-fields.md +5 -0
  162. package/skills/ape-plan-change/references/extensions.md +25 -0
  163. package/skills/ape-plan-change/references/finishing.md +3 -0
  164. package/skills/ape-plan-change/references/fix-from-error.md +3 -0
  165. package/skills/ape-plan-change/references/refactor.md +9 -0
  166. package/skills/ape-plan-change/references/structure.md +19 -0
  167. package/skills/ape-prototype/SKILL.md +13 -23
  168. package/skills/ape-prototype/references/comp.md +3 -0
  169. package/skills/ape-prototype/references/scope-and-export.md +5 -0
  170. package/skills/ape-prototype/references/snapshot.md +3 -0
  171. package/skills/ape-prototype/references/structure.md +11 -0
  172. package/skills/ape-prototype/references/working-app.md +7 -0
  173. package/skills/ape-request/SKILL.md +1 -1
  174. package/skills/ape-upgrade/SKILL.md +4 -1
  175. package/templates/product/package.json +1 -1
@@ -2,9 +2,12 @@ import { t as compatibleT } from '../compatible.js';
2
2
  import { add } from './add.js';
3
3
  import { exportProduct } from './export.js';
4
4
  import { checkExtensionGrants } from './grant-check.js';
5
+ import { newExtensionCommand } from './new.js';
6
+ import { packCommand } from './pack.js';
5
7
  import { t } from './places-messages.js';
6
8
  import { approvePlacesCommand } from './places-terminal.js';
7
9
  import { remove } from './remove.js';
10
+ import { t as shareText } from './share-text.js';
8
11
  import { t as stepsText } from './steps.js';
9
12
  /** `ape add`, `ape remove` and `ape export`: extensions in and out of a product (EXTENSIONS.md). */
10
13
  export function addExtensionCommands(program) {
@@ -14,11 +17,20 @@ export function addExtensionCommands(program) {
14
17
  .description(stepsText('extension.check.command'))
15
18
  .option('--json', compatibleT('compatible.json'))
16
19
  .action(checkExtensionGrants);
17
- program
18
- .command('extension')
20
+ const extension = program.command('extension');
21
+ extension
19
22
  .command('approve-places')
20
23
  .description(t('places.command'))
21
24
  .action(() => approvePlacesCommand());
25
+ extension
26
+ .command('new <key>')
27
+ .description(shareText('share.new.command'))
28
+ .action((key) => newExtensionCommand(key));
29
+ extension
30
+ .command('pack <key>')
31
+ .description(shareText('share.pack.command'))
32
+ .option('--out <folder>', shareText('share.pack.out'))
33
+ .action((key, options) => packCommand(key, options));
22
34
  program
23
35
  .command('add <name|path>')
24
36
  .description('Install an extension (development only): show what it asks for and ask, write its grant into buffcore.config.ts and the generated imports, migrate')
@@ -0,0 +1,16 @@
1
+ export declare class ShareRefused extends Error {
2
+ }
3
+ /**
4
+ * `ape extension new <key>`: a "build to share" piece starts as an extension in the product's
5
+ * `packages/`, from the same template `ape create --extension` writes: its own `<key>_` tables,
6
+ * words keyed `<key>.` that name no product, tests on its own small product, and its README as the
7
+ * agent's guide. The product's workspace already lists `packages/*`, so its tests run with the
8
+ * product's; installing it stays `ape add ./packages/<key>`.
9
+ */
10
+ export declare function newExtension(key: string, root?: string): Promise<{
11
+ key: string;
12
+ name: string;
13
+ path: string;
14
+ written: string[];
15
+ }>;
16
+ export declare function newExtensionCommand(key: string): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { findRoot } from '../../project.js';
6
+ import { BUFFCORE_RELEASE } from '../../version.js';
7
+ import { writeTemplates } from '../create-template.js';
8
+ import { readEditConfig } from './config-text.js';
9
+ import { t } from './share-text.js';
10
+ const template = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'templates', 'extension');
11
+ export class ShareRefused extends Error {
12
+ }
13
+ /**
14
+ * `ape extension new <key>`: a "build to share" piece starts as an extension in the product's
15
+ * `packages/`, from the same template `ape create --extension` writes: its own `<key>_` tables,
16
+ * words keyed `<key>.` that name no product, tests on its own small product, and its README as the
17
+ * agent's guide. The product's workspace already lists `packages/*`, so its tests run with the
18
+ * product's; installing it stays `ape add ./packages/<key>`.
19
+ */
20
+ export async function newExtension(key, root = findRoot()) {
21
+ if (!/^[a-z][a-z0-9]*$/.test(key))
22
+ throw new ShareRefused(t('share.new.key'));
23
+ if (!existsSync(join(root, 'buffcore.config.ts')))
24
+ throw new ShareRefused(t('share.new.product'));
25
+ if (/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/.test(key))
26
+ throw new ShareRefused(t('share.new.reserved', { key }));
27
+ if ((await readEditConfig(root)).grants[key])
28
+ throw new ShareRefused(t('share.new.installed', { key }));
29
+ const path = `packages/${key}`;
30
+ const dir = join(root, path);
31
+ if (existsSync(dir))
32
+ throw new ShareRefused(t('share.new.exists', { path }));
33
+ const Key = key[0]?.toUpperCase() + key.slice(1);
34
+ const { written } = await writeTemplates(dir, { name: key, key, Key, buffcore: BUFFCORE_RELEASE }, false, [template]);
35
+ // Inside a product, the sample product is the one its tests define; this product is its first user.
36
+ const readme = join(dir, 'README.md');
37
+ const text = await readFile(readme, 'utf8');
38
+ await writeFile(readme, text.replace(/^`packages\/\w+` is the extension; this repository is its first sample product\.$/m, `\`${path}\` is an extension built to share: its tests run their own small product, and this product is its first user.`));
39
+ return { key, name: `${key}-extension`, path, written };
40
+ }
41
+ export async function newExtensionCommand(key) {
42
+ try {
43
+ const made = await newExtension(key);
44
+ console.log(t('share.new.made', made));
45
+ }
46
+ catch (error) {
47
+ if (!(error instanceof ShareRefused))
48
+ throw error;
49
+ console.error(error.message);
50
+ process.exitCode = 1;
51
+ }
52
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * What `ape extension pack` may ship, as an allow-list: a file it can read as text (UTF-8, or
3
+ * UTF-16 with its byte-order mark), or an image or font whose printable runs it scans. Anything
4
+ * else (an archive, another binary, a file that does not decode) is refused and named. Dotfiles
5
+ * and dot-folders never ship, except a few known to hold no data; nor do credential, key and
6
+ * certificate files. Each file is read once: the bytes scanned are the bytes written.
7
+ */
8
+ export interface PackFile {
9
+ file: string;
10
+ bytes: Buffer;
11
+ /** The text the rules read: the file's own, or an image's or font's printable runs. */
12
+ text: string;
13
+ }
14
+ export type Unshippable = {
15
+ file: string;
16
+ why: 'hidden' | 'secretFile' | 'notText';
17
+ };
18
+ /** The file's text, or null when it is not text: UTF-16 by its mark, else strict UTF-8 with no NUL. */
19
+ export declare function decode(bytes: Buffer): string | null;
20
+ export declare function readPackage(dir: string): Promise<{
21
+ files: PackFile[];
22
+ refused: Unshippable[];
23
+ }>;
@@ -0,0 +1,78 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { SECRET_FILE } from '../check-secrets.js';
4
+ /** Built output and installed packages are not the package's own; they are neither read nor shipped. */
5
+ const SKIPPED_DIRS = new Set(['node_modules', 'dist', 'coverage']);
6
+ const SAFE_DOTFILES = new Set(['.gitignore', '.npmignore', '.editorconfig']);
7
+ /** Credentials, keys and certificates by their name, beyond `ape check secrets`' own list. */
8
+ const SECRET_NAME = /(^|\/)(credentials[^/]*\.json|secrets\.(ya?ml|json)|service-account[^/]*\.json|kubeconfig|\.envrc|\.npmrc|\.dev\.vars|id_[a-z0-9]+)$|\.(pem|key|crt|cer|der|p8|p12|pfx|ppk|jks|keystore|kdbx|gpg|asc|tfstate|tfstate\.backup)$/i;
9
+ /**
10
+ * Images and fonts may ship; their printable runs are scanned. Compressed data (woff2, a PNG's
11
+ * zTXt and iTXt chunks) cannot be read that way, so woff2 is not on the list.
12
+ */
13
+ const MEDIA = /\.(png|jpe?g|gif|webp|avif|ico|woff|ttf|otf)$/i;
14
+ /** Compressed by their kind, whatever their bytes look like: never shipped. */
15
+ const COMPRESSED = /\.(woff2|zip|gz|tgz|tar|7z|rar|jar|br|zst|xz|bz2)$/i;
16
+ async function walk(dir, at, out) {
17
+ for (const entry of await readdir(at, { withFileTypes: true })) {
18
+ if (entry.isSymbolicLink())
19
+ continue;
20
+ const path = join(at, entry.name);
21
+ if (entry.isDirectory()) {
22
+ if (!SKIPPED_DIRS.has(entry.name))
23
+ await walk(dir, path, out);
24
+ }
25
+ else if (entry.isFile())
26
+ out.push(relative(dir, path).split(sep).join('/'));
27
+ }
28
+ }
29
+ /** The file's text, or null when it is not text: UTF-16 by its mark, else strict UTF-8 with no NUL. */
30
+ export function decode(bytes) {
31
+ if (bytes[0] === 0xff && bytes[1] === 0xfe)
32
+ return bytes.subarray(2).toString('utf16le');
33
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) {
34
+ const swapped = Buffer.from(bytes.subarray(2));
35
+ swapped.swap16();
36
+ return swapped.toString('utf16le');
37
+ }
38
+ if (bytes.includes(0))
39
+ return null;
40
+ try {
41
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /** Printable ASCII runs of 6 or more, one a line: what `strings` would show of a binary. */
48
+ const runs = (bytes) => (bytes.toString('latin1').match(/[\x20-\x7e]{6,}/g) ?? []).join('\n');
49
+ export async function readPackage(dir) {
50
+ const names = [];
51
+ await walk(dir, dir, names);
52
+ const files = [];
53
+ const refused = [];
54
+ for (const file of names.sort()) {
55
+ if (file.split('/').some((part) => part.startsWith('.') && !SAFE_DOTFILES.has(part))) {
56
+ refused.push({
57
+ file,
58
+ why: SECRET_FILE.test(file) || SECRET_NAME.test(file) ? 'secretFile' : 'hidden',
59
+ });
60
+ continue;
61
+ }
62
+ if (SECRET_FILE.test(file) || SECRET_NAME.test(file)) {
63
+ refused.push({ file, why: 'secretFile' });
64
+ continue;
65
+ }
66
+ if (COMPRESSED.test(file)) {
67
+ refused.push({ file, why: 'notText' });
68
+ continue;
69
+ }
70
+ const bytes = await readFile(join(dir, file));
71
+ const text = MEDIA.test(file) ? runs(bytes) : decode(bytes);
72
+ if (text === null)
73
+ refused.push({ file, why: 'notText' });
74
+ else
75
+ files.push({ file, bytes, text });
76
+ }
77
+ return { files, refused };
78
+ }
@@ -0,0 +1,24 @@
1
+ import { type PackFile } from './pack-files.ts';
2
+ /**
3
+ * What `ape extension pack` refuses to hand on: a secret (the rules `ape check secrets` runs), an
4
+ * email or phone number that looks like a real person's, the product's own name, and any file it
5
+ * may not ship (`pack-files.ts`). A finding names the file and line, never the value. A value in
6
+ * the product's `secrets-allow.txt` (reviewed, public by design) is not a finding.
7
+ * Every pattern here runs in time linear in the line: each starts at a boundary and is capped.
8
+ * (Where a pattern is written, it is also spelled so that its own source does not match it.)
9
+ */
10
+ export interface Finding {
11
+ file: string;
12
+ line?: number;
13
+ kind: 'secret' | 'secretFile' | 'hidden' | 'notText' | 'email' | 'phone' | 'name' | 'nameFile';
14
+ message: string;
15
+ }
16
+ /** A text's words, lower case: split at every non-letter-or-digit and at camelCase, in one pass. */
17
+ export declare function words(text: string): string[];
18
+ /** Each finding in one file's text; `allowed` are the product's reviewed public values. */
19
+ export declare function scanText(file: string, text: string, productName: string, allowed?: readonly string[]): Finding[];
20
+ /** Every finding in the package, and the files to ship: exactly the bytes that were scanned. */
21
+ export declare function scanPackage(dir: string, productName: string, allowed?: readonly string[]): Promise<{
22
+ files: PackFile[];
23
+ findings: Finding[];
24
+ }>;
@@ -0,0 +1,131 @@
1
+ import { secretHits } from '../check-secrets.js';
2
+ import { readPackage } from './pack-files.js';
3
+ import { t } from './share-text.js';
4
+ /** A local part of 1 to 64 characters starting at a boundary, then up to 8 labels of 63. */
5
+ const EMAIL = /(?<![\w.+-])[\w.+-]{1,64}@([a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63}){1,8})(?![\w-])/gi;
6
+ /** Domains kept for examples and tests (RFC 2606, 6761), and placeholders. */
7
+ const EXAMPLE_DOMAIN = /(?:^|\.)(?:example\.(?:com|net|org)|[\w-]+\.(?:test|example|invalid|localhost|local|internal))$|^(?:example|localhost)$/i;
8
+ /** Endings that are a file's, not a domain's: `logo@2x.png`, `icon@3x.webp`. */
9
+ const FILE_ENDING = /^(?:png|jpe?g|gif|svg|webp|avif|ico|bmp|tiff?|js|mjs|cjs|ts|tsx|jsx|json|css|scss|html?|md|txt|xml|ya?ml|map|wasm|woff2?|ttf|otf|mp[34]|mov|pdf|zip|gz|tgz|lock)$/i;
10
+ /** A real-looking address: its last label letters and not a file ending, no label all digits. */
11
+ function realEmail(domain) {
12
+ const labels = domain.split('.');
13
+ const tld = labels.at(-1) ?? '';
14
+ if (!/^[a-z]{2,24}$/i.test(tld) || FILE_ENDING.test(tld))
15
+ return false;
16
+ if (labels.some((label) => /^\d+$/.test(label)))
17
+ return false;
18
+ return !EXAMPLE_DOMAIN.test(domain);
19
+ }
20
+ /**
21
+ * Phone numbers, kept to shapes a real number has so dates, versions, ids and drawings pass:
22
+ * - a `+` and a country code with 10 to 15 digits however grouped;
23
+ * - North American 3-3-4 with separators, unless it is one of a run of numbers (an SVG path,
24
+ * `M 210 320 1240`): never after a path command letter or a number, never before a number;
25
+ * - 10 digits alone, area code and exchange starting 2 to 9, only as a whole quoted value or after
26
+ * `tel:` (a bare constant such as 2147483647 is a number, not a phone);
27
+ * - a UK number from 0 (07xxx xxxxxx, or 0 and 10 digits alone).
28
+ * The fictional ranges pass: 555-0100 to 555-0199, and 07700 900000 to 900999.
29
+ */
30
+ const PHONES = [
31
+ /(?<![\w.+])\+\d(?:[\s.-]?\(?\d\)?){9,14}(?![\w.])/g,
32
+ /(?<![\w.]|\d[\s,]{1,3}|(?:^|[\s,"'])[MLHVCSQTAZmlhvcsqtaz][\s,]?)\(?[2-9]\d{2}\)?[\s.-]\d{3}[\s.-]\d{4}(?![\w.]|[\s,]{1,3}-?\d)/g,
33
+ /(?<=['"`>]|tel:)[2-9]\d{2}[2-9]\d{6}(?=['"`<])/g,
34
+ /(?<![\w.-])0[1-9]\d{3}[\s-]?\d{6}(?![\w.-])/g,
35
+ ];
36
+ const FICTIONAL_PHONE = /555[\s.)-]*01\d\d|7700[\s.-]?900\d{3}/;
37
+ const NOT_PHONES = new Set(['2147483647', '2147483648', '4294967295', '4294967296']);
38
+ const phonesIn = (line) => PHONES.flatMap((pattern) => [...line.matchAll(pattern)]
39
+ .map(([phone]) => phone)
40
+ .filter((phone) => !FICTIONAL_PHONE.test(phone) && !NOT_PHONES.has(phone)));
41
+ /** A text's words, lower case: split at every non-letter-or-digit and at camelCase, in one pass. */
42
+ export function words(text) {
43
+ const out = [];
44
+ let word = '';
45
+ for (let i = 0; i < text.length; i++) {
46
+ const c = text[i];
47
+ const lower = c >= 'a' && c <= 'z';
48
+ const upper = c >= 'A' && c <= 'Z';
49
+ if (!lower && !upper && !(c >= '0' && c <= '9')) {
50
+ if (word)
51
+ out.push(word);
52
+ word = '';
53
+ continue;
54
+ }
55
+ const before = text[i - 1] ?? '';
56
+ const next = text[i + 1] ?? '';
57
+ // `brightPaws`, `v2Api`: a capital after a small letter or digit; `HTTPServer`: the last
58
+ // capital of a run when a small letter follows.
59
+ const startsWord = upper &&
60
+ word !== '' &&
61
+ (/[a-z0-9]/.test(before) || (/[A-Z]/.test(before) && next >= 'a' && next <= 'z'));
62
+ if (startsWord) {
63
+ out.push(word);
64
+ word = '';
65
+ }
66
+ word += c.toLowerCase();
67
+ }
68
+ if (word)
69
+ out.push(word);
70
+ return out;
71
+ }
72
+ /**
73
+ * The product's name in any spelling: `bright-paws`, `Bright Paws`, `brightPawsApi`, `BRIGHTPAWS`.
74
+ * Its letters joined must equal one to four neighbouring words joined.
75
+ */
76
+ function namedIn(name) {
77
+ const joined = words(name).join('');
78
+ return (text) => {
79
+ const list = words(text);
80
+ for (let start = 0; start < list.length; start++) {
81
+ let run = '';
82
+ for (let end = start; end < Math.min(list.length, start + 4); end++) {
83
+ run += list[end];
84
+ if (run === joined)
85
+ return true;
86
+ if (run.length >= joined.length)
87
+ break;
88
+ }
89
+ }
90
+ return false;
91
+ };
92
+ }
93
+ /** Each finding in one file's text; `allowed` are the product's reviewed public values. */
94
+ export function scanText(file, text, productName, allowed = []) {
95
+ const found = [];
96
+ const add = (kind, line, values = {}) => found.push({ file, line, kind, message: t(`share.pack.${kind}`, { file, line, ...values }) });
97
+ const reviewed = (value) => allowed.some((entry) => entry.includes(value));
98
+ for (const { line, rule } of secretHits(text, allowed))
99
+ add('secret', line, { rule });
100
+ const named = namedIn(productName);
101
+ for (const [index, raw] of text.split('\n').entries()) {
102
+ const line = index + 1;
103
+ if ([...raw.matchAll(EMAIL)].some(([email, domain]) => realEmail(domain ?? '') && !reviewed(email)))
104
+ add('email', line);
105
+ if (phonesIn(raw).some((phone) => !reviewed(phone)))
106
+ add('phone', line);
107
+ if (named(raw))
108
+ add('name', line, { name: productName });
109
+ }
110
+ return found;
111
+ }
112
+ /** Every finding in the package, and the files to ship: exactly the bytes that were scanned. */
113
+ export async function scanPackage(dir, productName, allowed = []) {
114
+ const { files, refused } = await readPackage(dir);
115
+ const findings = refused.map(({ file, why }) => ({
116
+ file,
117
+ kind: why,
118
+ message: t(`share.pack.${why}`, { file }),
119
+ }));
120
+ const named = namedIn(productName);
121
+ for (const { file, text } of files) {
122
+ if (named(file))
123
+ findings.push({
124
+ file,
125
+ kind: 'nameFile',
126
+ message: t('share.pack.nameFile', { file, name: productName }),
127
+ });
128
+ findings.push(...scanText(file, text, productName, allowed));
129
+ }
130
+ return { files, findings };
131
+ }
@@ -0,0 +1,48 @@
1
+ import { type Finding } from './pack-scan.ts';
2
+ /** The extension checks' result as the bundle records it; `ape check compatible` gives it. */
3
+ export interface CheckReport {
4
+ ok: boolean;
5
+ checks?: unknown;
6
+ problem?: string;
7
+ }
8
+ type RunChecks = (dir: string, root: string) => Promise<CheckReport>;
9
+ export type PackResult = {
10
+ ok: false;
11
+ findings: Finding[];
12
+ message?: string;
13
+ } | {
14
+ ok: true;
15
+ path: string;
16
+ submission: Submission;
17
+ checks: CheckReport;
18
+ };
19
+ interface Submission {
20
+ package: string;
21
+ version: string;
22
+ key: string;
23
+ catalog: string | null;
24
+ license: string;
25
+ touches: {
26
+ reads: string[];
27
+ hosts: string[];
28
+ places: string[];
29
+ uploads: string[];
30
+ } | null;
31
+ screens: string[];
32
+ files: string[];
33
+ }
34
+ /**
35
+ * `ape extension pack <key>`: a submission bundle for the catalog the product names, written to a
36
+ * local folder (`.ape/pack/<key>/` by default). It holds `package/` (the package's own files),
37
+ * `check-report.json` (the extension checks), `scan.json` (what was looked for and found) and
38
+ * `submission.json` (what it can touch, its licence, its screens). It refuses a package holding a
39
+ * secret, a real-looking email or phone, or the product's own name, listing each. It never
40
+ * publishes, uploads or calls the network: a person submits the folder.
41
+ */
42
+ export declare function pack(key: string, options?: {
43
+ out?: string;
44
+ }, root?: string, runChecks?: RunChecks): Promise<PackResult>;
45
+ export declare function packCommand(key: string, options: {
46
+ out?: string;
47
+ }): Promise<void>;
48
+ export {};
@@ -0,0 +1,142 @@
1
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
2
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { findRoot } from '../../project.js';
5
+ import { allowedValues } from '../check-secrets.js';
6
+ import { readEditConfig } from './config-text.js';
7
+ import { scanPackage } from './pack-scan.js';
8
+ import { t } from './share-text.js';
9
+ import { readPackage } from './surfaces.js';
10
+ const runCompatible = async (dir, root) => {
11
+ try {
12
+ const { compatible } = await import('../compatible.js');
13
+ const result = await compatible(dir, root);
14
+ return { ok: result.ok, checks: result.checks };
15
+ }
16
+ catch (error) {
17
+ // The bundle leaves this computer: its folders are named from the product's root.
18
+ const problem = error instanceof Error ? error.message : String(error);
19
+ return { ok: false, problem: problem.replaceAll(root, '.') };
20
+ }
21
+ };
22
+ const MARKER = '.ape-pack-bundle';
23
+ /**
24
+ * Where the bundle goes: `.ape/pack/<key>` in the product, or `--out <folder>`, a path from the
25
+ * product's root that stays inside `.ape/pack/`. Absolute paths and `..` are refused, and so is an
26
+ * existing folder pack did not write: nothing else is ever deleted.
27
+ */
28
+ function bundleFolder(root, key, given) {
29
+ const base = resolve(root, '.ape', 'pack');
30
+ const refuse = { message: t('share.pack.outside', { out: given ?? '' }) };
31
+ if (given !== undefined &&
32
+ (isAbsolute(given) || /^[\\/]|^[a-z]:/i.test(given) || given.split(/[\\/]/).includes('..')))
33
+ return refuse;
34
+ const folder = join(given === undefined ? base : resolve(root, given), key);
35
+ const inside = relative(base, folder);
36
+ if (!inside || inside.startsWith('..') || isAbsolute(inside))
37
+ return refuse;
38
+ // Each step from the product down to the bundle is a real folder: a link or junction on the way
39
+ // (`.ape` itself included) could point outside, so it is refused, not followed.
40
+ let at = root;
41
+ for (const part of relative(root, folder).split(sep)) {
42
+ at = join(at, part);
43
+ if (!existsSync(at))
44
+ break;
45
+ if (lstatSync(at).isSymbolicLink() ||
46
+ realpathSync(at) !== join(realpathSync(root), relative(root, at)))
47
+ return refuse;
48
+ }
49
+ if (existsSync(folder) && !existsSync(join(folder, MARKER)))
50
+ return {
51
+ message: t('share.pack.notBundle', { path: relative(root, folder).split(sep).join('/') }),
52
+ };
53
+ return folder;
54
+ }
55
+ /**
56
+ * `ape extension pack <key>`: a submission bundle for the catalog the product names, written to a
57
+ * local folder (`.ape/pack/<key>/` by default). It holds `package/` (the package's own files),
58
+ * `check-report.json` (the extension checks), `scan.json` (what was looked for and found) and
59
+ * `submission.json` (what it can touch, its licence, its screens). It refuses a package holding a
60
+ * secret, a real-looking email or phone, or the product's own name, listing each. It never
61
+ * publishes, uploads or calls the network: a person submits the folder.
62
+ */
63
+ export async function pack(key, options = {}, root = findRoot(), runChecks = runCompatible) {
64
+ const dir = join(root, 'packages', key);
65
+ if (!/^[a-z][a-z0-9]*$/.test(key) || !existsSync(join(dir, 'package.json')))
66
+ return {
67
+ ok: false,
68
+ findings: [],
69
+ message: t('share.pack.missing', { path: `packages/${key}` }),
70
+ };
71
+ const config = await readEditConfig(root);
72
+ const { files: shipped, findings } = await scanPackage(dir, config.name(), allowedValues(root));
73
+ const files = shipped.map(({ file }) => file);
74
+ if (findings.length)
75
+ return { ok: false, findings };
76
+ const json = readPackage(dir);
77
+ const grant = config.grants[key];
78
+ const exportsOf = (json.exports ?? {});
79
+ const submission = {
80
+ package: json.name ?? `${key}-extension`,
81
+ version: json.version ?? '0.0.0',
82
+ key,
83
+ catalog: config.catalog().catalog?.url ?? null,
84
+ license: json.license ?? 'UNLICENSED',
85
+ touches: grant
86
+ ? {
87
+ reads: [...(grant.reads ?? [])],
88
+ hosts: [...(grant.hosts ?? [])],
89
+ places: [...(grant.places ?? [])],
90
+ uploads: [...(grant.uploads ?? [])],
91
+ }
92
+ : null,
93
+ screens: files.filter((file) => (('./admin' in exportsOf && file.startsWith('src/admin/')) ||
94
+ ('./app' in exportsOf && file.startsWith('src/app/'))) &&
95
+ /View\.tsx$/.test(file)),
96
+ files,
97
+ };
98
+ const out = bundleFolder(root, key, options.out);
99
+ if (typeof out !== 'string')
100
+ return { ok: false, findings: [], message: out.message };
101
+ const checks = await runChecks(dir, root);
102
+ // Only a folder pack made (its marker inside) is replaced; the bytes written are those scanned.
103
+ await rm(out, { recursive: true, force: true });
104
+ for (const { file, bytes } of shipped) {
105
+ await mkdir(dirname(join(out, 'package', file)), { recursive: true });
106
+ await writeFile(join(out, 'package', file), bytes);
107
+ }
108
+ await writeFile(join(out, MARKER), '');
109
+ const write = (file, value) => writeFile(join(out, file), `${JSON.stringify(value, null, 2)}\n`);
110
+ await write('submission.json', submission);
111
+ await write('check-report.json', checks);
112
+ await write('scan.json', {
113
+ looked: ['secrets', 'secret files', 'emails', 'phone numbers', 'the product name'],
114
+ findings: [],
115
+ });
116
+ return { ok: true, path: relative(root, out).split(sep).join('/'), submission, checks };
117
+ }
118
+ const list = (values) => values?.length ? values.join(', ') : t('share.pack.none');
119
+ export async function packCommand(key, options) {
120
+ const result = await pack(key, options);
121
+ if (!result.ok) {
122
+ if (result.message)
123
+ console.error(result.message);
124
+ else {
125
+ console.error(t('share.pack.refused', { count: result.findings.length }));
126
+ for (const finding of result.findings)
127
+ console.error(` ${finding.message}`);
128
+ }
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ const { submission: s, checks } = result;
133
+ console.log(t('share.pack.done', { path: result.path, catalog: s.catalog ?? t('share.pack.noCatalog') }));
134
+ console.log(t('share.pack.touches', {
135
+ reads: list(s.touches?.reads),
136
+ hosts: list(s.touches?.hosts),
137
+ places: list(s.touches?.places),
138
+ }));
139
+ console.log(t('share.pack.license', { license: s.license }));
140
+ console.log(t('share.pack.screens', { screens: list(s.screens) }));
141
+ console.log(t('share.pack.checks', { state: t(checks.ok ? 'share.pack.passed' : 'share.pack.failed') }));
142
+ }
@@ -0,0 +1,3 @@
1
+ import { en } from './share.en.ts';
2
+ /** The words of `ape extension new` and `ape extension pack`, in the terminal's language. */
3
+ export declare const t: (key: keyof typeof en, values?: Record<string, unknown>) => string;
@@ -0,0 +1,6 @@
1
+ import { createI18n } from '@buffcore/i18n';
2
+ import { en } from './share.en.js';
3
+ import { es } from './share.es.js';
4
+ const messages = createI18n({ catalogs: [{ en, es }] });
5
+ /** The words of `ape extension new` and `ape extension pack`, in the terminal's language. */
6
+ export const t = (key, values) => messages.t(/^es(?:[-_.]|$)/i.test(process.env.LC_ALL || process.env.LANG || '') ? 'es' : 'en', key, values);
@@ -0,0 +1,32 @@
1
+ export declare const en: {
2
+ readonly 'share.new.command': 'Start an extension built to share in this product: packages/<key> with its own tables, neutral words, tests on its own small product and its guide';
3
+ readonly 'share.new.key': 'The key is lowercase letters and digits, starting with a letter (sms, invoices2)';
4
+ readonly 'share.new.product': 'Run it in a product: no buffcore.config.ts here';
5
+ readonly 'share.new.exists': '{path} already exists: pick another key, or keep building that one';
6
+ readonly 'share.new.made': "Started {path} ({name}). Install it with pnpm ape add ./{path}; its tests run with the product's, and pnpm ape check compatible ./{path} checks it as the catalog will.";
7
+ readonly 'share.pack.command': 'Write a submission bundle for the catalog the product names: the package, its check report and the scan. Never publishes or calls the network';
8
+ readonly 'share.pack.out': 'the folder the bundle goes in (default .ape/pack)';
9
+ readonly 'share.pack.missing': 'No extension at {path} (pnpm ape extension new <key> starts one)';
10
+ readonly 'share.pack.refused': 'Not packed: {count, plural, one {# finding} other {# findings}} to take out first (each named, never its value):';
11
+ readonly 'share.pack.secret': '{file}:{line}: a secret ({rule})';
12
+ readonly 'share.pack.secretFile': '{file}: a secret or data file, by its name';
13
+ readonly 'share.pack.email': '{file}:{line}: an email address that looks real (use example.com)';
14
+ readonly 'share.pack.phone': '{file}:{line}: a phone number that looks real (use 555-0100 to 555-0199)';
15
+ readonly 'share.pack.name': '{file}:{line}: the product\'s own name, "{name}" (an extension\'s words name no product)';
16
+ readonly 'share.pack.nameFile': '{file}: the product\'s own name, "{name}", in its path';
17
+ readonly 'share.pack.hidden': '{file}: a hidden file or folder, never shipped (only .gitignore, .npmignore and .editorconfig are)';
18
+ readonly 'share.pack.notText': '{file}: not text pack can scan (an archive or another binary); only text, images and fonts ship';
19
+ readonly 'share.pack.outside': 'The bundle goes inside .ape/pack/ in the product: {out} is not there';
20
+ readonly 'share.pack.notBundle': '{path} exists and is not a bundle pack wrote; move it away first';
21
+ readonly 'share.new.installed': '{key} is installed already: pick another key, or its tables would clash';
22
+ readonly 'share.new.reserved': '{key} is a name Windows keeps for itself: pick another key';
23
+ readonly 'share.pack.done': 'Bundle written to {path}, for {catalog}. Nothing was sent: a person submits it.';
24
+ readonly 'share.pack.noCatalog': 'no catalog named in buffcore.config.ts yet';
25
+ readonly 'share.pack.checks': 'Checks: {state}. The report is check-report.json.';
26
+ readonly 'share.pack.passed': 'passed';
27
+ readonly 'share.pack.failed': 'not passed yet, see the report';
28
+ readonly 'share.pack.touches': 'It can touch: reads {reads}; hosts {hosts}; places {places}';
29
+ readonly 'share.pack.license': 'Licence: {license}';
30
+ readonly 'share.pack.screens': 'Screens: {screens}';
31
+ readonly 'share.pack.none': 'none';
32
+ };
@@ -0,0 +1,32 @@
1
+ export const en = {
2
+ 'share.new.command': 'Start an extension built to share in this product: packages/<key> with its own tables, neutral words, tests on its own small product and its guide',
3
+ 'share.new.key': 'The key is lowercase letters and digits, starting with a letter (sms, invoices2)',
4
+ 'share.new.product': 'Run it in a product: no buffcore.config.ts here',
5
+ 'share.new.exists': '{path} already exists: pick another key, or keep building that one',
6
+ 'share.new.made': "Started {path} ({name}). Install it with pnpm ape add ./{path}; its tests run with the product's, and pnpm ape check compatible ./{path} checks it as the catalog will.",
7
+ 'share.pack.command': 'Write a submission bundle for the catalog the product names: the package, its check report and the scan. Never publishes or calls the network',
8
+ 'share.pack.out': 'the folder the bundle goes in (default .ape/pack)',
9
+ 'share.pack.missing': 'No extension at {path} (pnpm ape extension new <key> starts one)',
10
+ 'share.pack.refused': 'Not packed: {count, plural, one {# finding} other {# findings}} to take out first (each named, never its value):',
11
+ 'share.pack.secret': '{file}:{line}: a secret ({rule})',
12
+ 'share.pack.secretFile': '{file}: a secret or data file, by its name',
13
+ 'share.pack.email': '{file}:{line}: an email address that looks real (use example.com)',
14
+ 'share.pack.phone': '{file}:{line}: a phone number that looks real (use 555-0100 to 555-0199)',
15
+ 'share.pack.name': '{file}:{line}: the product\'s own name, "{name}" (an extension\'s words name no product)',
16
+ 'share.pack.nameFile': '{file}: the product\'s own name, "{name}", in its path',
17
+ 'share.pack.hidden': '{file}: a hidden file or folder, never shipped (only .gitignore, .npmignore and .editorconfig are)',
18
+ 'share.pack.notText': '{file}: not text pack can scan (an archive or another binary); only text, images and fonts ship',
19
+ 'share.pack.outside': 'The bundle goes inside .ape/pack/ in the product: {out} is not there',
20
+ 'share.pack.notBundle': '{path} exists and is not a bundle pack wrote; move it away first',
21
+ 'share.new.installed': '{key} is installed already: pick another key, or its tables would clash',
22
+ 'share.new.reserved': '{key} is a name Windows keeps for itself: pick another key',
23
+ 'share.pack.done': 'Bundle written to {path}, for {catalog}. Nothing was sent: a person submits it.',
24
+ 'share.pack.noCatalog': 'no catalog named in buffcore.config.ts yet',
25
+ 'share.pack.checks': 'Checks: {state}. The report is check-report.json.',
26
+ 'share.pack.passed': 'passed',
27
+ 'share.pack.failed': 'not passed yet, see the report',
28
+ 'share.pack.touches': 'It can touch: reads {reads}; hosts {hosts}; places {places}',
29
+ 'share.pack.license': 'Licence: {license}',
30
+ 'share.pack.screens': 'Screens: {screens}',
31
+ 'share.pack.none': 'none',
32
+ };
@@ -0,0 +1,2 @@
1
+ import type { en } from './share.en.ts';
2
+ export declare const es: Record<keyof typeof en, string>;