@actioneer/ads 0.2.2 → 0.2.4

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/bin/ads-init.mjs CHANGED
@@ -12,8 +12,10 @@
12
12
  * • inject `@import "@actioneer/ads/styles.css";` right after
13
13
  * `@import "tailwindcss";` in the global stylesheet
14
14
  * • scaffold the three required providers (TooltipProvider, ToastProvider,
15
- * <MotionConfig reducedMotion="user">) as `app/providers.tsx` and wrap the
16
- * root layout's children with them
15
+ * <MotionConfig reducedMotion="user">) into a CLI-OWNED `ads-providers.{tsx,jsx}`
16
+ * (never the user's own `providers.*` — see the overwrite-safety guard) and
17
+ * wrap the root layout's children with them. The file extension + whether it
18
+ * carries TS type annotations follow the project language (TS vs JS).
17
19
  * • drop a consumer-mode `ads-lint.config.mjs`
18
20
  * (`libraryPackage: "@actioneer/ads"`, `libraryRoot: null`)
19
21
  *
@@ -40,6 +42,7 @@ const STYLE_IMPORT = `@import "${PKG}/styles.css";`;
40
42
  * @property {string|null} layoutPath repo-relative path to the root layout (or null)
41
43
  * @property {string|null} layoutContent
42
44
  * @property {boolean} hasAdsLintConfig
45
+ * @property {"ts"|"js"} [language] consumer project language (default "ts")
43
46
  * @property {"npm"|"pnpm"|"yarn"|"bun"} [packageManager] detected consumer PM (default npm)
44
47
  *
45
48
  * @typedef {Object} Edit
@@ -132,16 +135,21 @@ export function planInit(state) {
132
135
  });
133
136
  }
134
137
 
135
- // 3. Scaffold the providers file + wrap the layout.
138
+ // 3. Scaffold the CLI-OWNED providers file + wrap the layout.
139
+ // We write `ads-providers.{tsx,jsx}` (NOT `providers.*`) so a consumer's own
140
+ // `providers.tsx` is never touched or trusted, and the layout imports
141
+ // { Providers } from OUR file. Extension + TS annotations follow the language.
142
+ const language = state.language === "js" ? "js" : "ts";
143
+ const providersBasename = language === "js" ? "ads-providers.jsx" : "ads-providers.tsx";
136
144
  if (state.layoutPath != null) {
137
145
  const dir = path.posix.dirname(toPosix(state.layoutPath));
138
- const providersPath = path.posix.join(dir, "providers.tsx");
146
+ const providersPath = path.posix.join(dir, providersBasename);
139
147
  if (!fileExistsInState(state, providersPath)) {
140
148
  edits.push({
141
149
  type: "write-file",
142
150
  title: `scaffold providers at ${providersPath}`,
143
151
  path: providersPath,
144
- content: PROVIDERS_FILE,
152
+ content: providersFile(language),
145
153
  });
146
154
  }
147
155
  if (state.layoutContent != null && !state.layoutContent.includes("<Providers>")) {
@@ -154,25 +162,25 @@ export function planInit(state) {
154
162
  find: child,
155
163
  findIndex: state.layoutContent.indexOf(child, state.layoutContent.indexOf("return")),
156
164
  replace: `<Providers>${child}</Providers>`,
157
- addImport: `import { Providers } from "./providers";`,
165
+ addImport: `import { Providers } from "./ads-providers";`,
158
166
  });
159
167
  } else {
160
168
  edits.push({
161
169
  type: "manual",
162
- title: `wrap your app root's children with <Providers> (from ./providers)`,
170
+ title: `wrap your app root's children with <Providers> (from ./ads-providers)`,
163
171
  });
164
172
  }
165
173
  }
166
174
  } else {
167
175
  edits.push({
168
176
  type: "write-file",
169
- title: "scaffold providers at app/providers.tsx",
170
- path: "app/providers.tsx",
171
- content: PROVIDERS_FILE,
177
+ title: `scaffold providers at app/${providersBasename}`,
178
+ path: `app/${providersBasename}`,
179
+ content: providersFile(language),
172
180
  });
173
181
  edits.push({
174
182
  type: "manual",
175
- title: "wrap your app root's children with <Providers> (from ./providers)",
183
+ title: "wrap your app root's children with <Providers> (from ./ads-providers)",
176
184
  });
177
185
  }
178
186
 
@@ -212,7 +220,18 @@ export function findJsxChildren(source) {
212
220
  return null;
213
221
  }
214
222
 
215
- const PROVIDERS_FILE = `"use client";
223
+ /**
224
+ * The ADS providers scaffold, generated for the consumer's language. A TS project
225
+ * gets the typed signature; a JS project gets a plain signature with NO TypeScript
226
+ * annotations (a `: { children: React.ReactNode }` in a `.jsx`/`.js` file is a
227
+ * syntax error). The file extension is chosen by the caller (`ads-providers.tsx`
228
+ * vs `ads-providers.jsx`).
229
+ * @param {"ts"|"js"} language
230
+ */
231
+ export function providersFile(language) {
232
+ const signature =
233
+ language === "js" ? "{ children }" : "{ children }: { children: React.ReactNode }";
234
+ return `"use client";
216
235
 
217
236
  // Required ADS providers — wrap the app root once. Without TooltipProvider the
218
237
  // vendored tooltip/attachment chips crash; ToastProvider is needed to render
@@ -220,7 +239,7 @@ const PROVIDERS_FILE = `"use client";
220
239
  import { TooltipProvider, ToastProvider } from "${PKG}";
221
240
  import { MotionConfig } from "motion/react";
222
241
 
223
- export function Providers({ children }: { children: React.ReactNode }) {
242
+ export function Providers(${signature}) {
224
243
  return (
225
244
  <MotionConfig reducedMotion="user">
226
245
  <ToastProvider>
@@ -230,6 +249,63 @@ export function Providers({ children }: { children: React.ReactNode }) {
230
249
  );
231
250
  }
232
251
  `;
252
+ }
253
+
254
+ /**
255
+ * Detect the consumer project's language. The chosen root layout's extension is
256
+ * the most authoritative signal (`.tsx`/`.ts` → TS, `.jsx`/`.js` → JS); with no
257
+ * layout, presence of a tsconfig.json decides, defaulting to JS. Drives whether
258
+ * the scaffolded providers file is `.tsx` (typed) or `.jsx` (untyped).
259
+ * @param {{layoutPath?:string|null, hasTsconfig?:boolean}} [signals]
260
+ * @returns {"ts"|"js"}
261
+ */
262
+ export function detectLanguage({ layoutPath, hasTsconfig } = {}) {
263
+ if (layoutPath) {
264
+ if (/\.tsx?$/.test(layoutPath)) return "ts";
265
+ if (/\.jsx?$/.test(layoutPath)) return "js";
266
+ }
267
+ return hasTsconfig ? "ts" : "js";
268
+ }
269
+
270
+ /**
271
+ * Insert an import line into module source, DIRECTIVE-AWARE. If the file opens
272
+ * with a directive prologue (`"use client"` / `'use server'` / `"use strict"`,
273
+ * possibly after leading comments/blank lines), the import lands AFTER the last
274
+ * such directive so the directive stays the first statement — otherwise Next
275
+ * treats a `"use client"` layout as a Server Component and `next build` breaks.
276
+ * With no directive, the import prepends to the very top. Idempotent.
277
+ */
278
+ export function insertImport(content, importLine) {
279
+ if (content.includes(importLine)) return content;
280
+ const lines = content.split("\n");
281
+ const directiveRe = /^(["'])use [\w-]+\1\s*;?$/;
282
+ let i = 0;
283
+ let insertAt = 0; // default: the very top
284
+ while (i < lines.length) {
285
+ const trimmed = lines[i].trim();
286
+ if (trimmed === "") {
287
+ i++;
288
+ continue;
289
+ }
290
+ if (trimmed.startsWith("//")) {
291
+ i++;
292
+ continue;
293
+ }
294
+ if (trimmed.startsWith("/*")) {
295
+ while (i < lines.length && !lines[i].includes("*/")) i++;
296
+ if (i < lines.length) i++; // consume the closing line
297
+ continue;
298
+ }
299
+ if (directiveRe.test(trimmed)) {
300
+ i++;
301
+ insertAt = i; // land after this (the last-seen) directive
302
+ continue;
303
+ }
304
+ break; // first real code line — stop scanning
305
+ }
306
+ lines.splice(insertAt, 0, importLine);
307
+ return lines.join("\n");
308
+ }
233
309
 
234
310
  const ADS_LINT_CONFIG = `// @actioneer/ads-lint — consumer mode. Every file is a consumer, so the
235
311
  // barrel / deep-import / external-UI rules apply everywhere. See the ADS
@@ -252,7 +328,22 @@ const CANDIDATE_CSS = [
252
328
  "app/global.css",
253
329
  "src/styles/globals.css",
254
330
  ];
255
- const CANDIDATE_LAYOUT = ["app/layout.tsx", "src/app/layout.tsx", "app/layout.jsx", "src/app/layout.jsx"];
331
+ // `create-next-app` emits `app/layout.js` for a JS project and `app/layout.tsx`
332
+ // for TS, under `app/` or `src/app/`. All six must be recognized or a fresh JS
333
+ // repo is never bootstrapped (#3).
334
+ const CANDIDATE_LAYOUT = [
335
+ "app/layout.tsx",
336
+ "src/app/layout.tsx",
337
+ "app/layout.jsx",
338
+ "src/app/layout.jsx",
339
+ "app/layout.js",
340
+ "src/app/layout.js",
341
+ ];
342
+
343
+ /** The chosen root layout among the conventional locations (or null). */
344
+ function detectLayoutPath(cwd) {
345
+ return CANDIDATE_LAYOUT.find((p) => fs.existsSync(path.join(cwd, p))) ?? null;
346
+ }
256
347
 
257
348
  // The load-bearing anchor: ADS styles must import into the SAME CSS graph as
258
349
  // tailwindcss, right after it (styles.css before tailwindcss leaves @theme
@@ -271,20 +362,53 @@ function fileExistsInState(state, relPosix) {
271
362
  }
272
363
 
273
364
  /**
274
- * Find the global stylesheet to wire ADS styles into. Because the import order
275
- * is load-bearing, detection PREFERS the stylesheet that already imports
276
- * tailwindcss — first among the conventional locations, then ANYWHERE in the
277
- * project (bounded scan) so a non-standard path (e.g. `src/index.css`,
278
- * `app/tailwind.css`) is auto-wired instead of degrading to a hand-edit note.
279
- * Falls back to the first conventional file that exists (→ manual, with anchor
280
- * guidance), else null.
365
+ * Find the global stylesheet to wire ADS styles into. Detection is BOUND TO THE
366
+ * SELECTED LAYOUT first (#8): the stylesheet the chosen root layout actually
367
+ * imports (or one adjacent to it) is the sheet that loads, so a stale
368
+ * `app/globals.css` can't get the ADS import while the real `src/app/...` layout
369
+ * imports a different sheet. Only when the layout yields nothing do we fall back
370
+ * to the flat scan. Because the import order is load-bearing, each tier PREFERS
371
+ * the stylesheet that already imports tailwindcss — the conventional locations,
372
+ * then ANYWHERE in the project (bounded scan) so a non-standard path (e.g.
373
+ * `src/index.css`, `app/tailwind.css`) is auto-wired instead of degrading to a
374
+ * hand-edit note. Falls back to the first conventional file that exists (→ manual,
375
+ * with anchor guidance), else null.
376
+ * @param {string} cwd
377
+ * @param {string|null} [layoutPath] the selected root layout (repo-relative), to bind CSS discovery to
281
378
  * @returns {{path: string|null, content: string|null}}
282
379
  */
283
- export function detectGlobalCss(cwd) {
380
+ export function detectGlobalCss(cwd, layoutPath = null) {
284
381
  const read = (rel) => {
285
382
  const abs = path.join(cwd, rel);
286
383
  return fs.existsSync(abs) ? fs.readFileSync(abs, "utf8") : null;
287
384
  };
385
+
386
+ // 0. Layout-anchored: the stylesheet the SELECTED layout imports (resolved
387
+ // relative to the layout dir), or a globals.css adjacent to it.
388
+ if (layoutPath) {
389
+ const layoutContent = read(layoutPath);
390
+ const layoutDir = path.posix.dirname(toPosix(layoutPath));
391
+ if (layoutContent != null) {
392
+ let firstImported = null;
393
+ for (const m of layoutContent.matchAll(/import\s+["']([^"']+\.css)["']/g)) {
394
+ const spec = m[1];
395
+ if (!spec.startsWith(".")) continue; // skip package/alias CSS imports
396
+ const rel = toPosix(path.posix.normalize(path.posix.join(layoutDir, spec)));
397
+ const c = read(rel);
398
+ if (c == null) continue;
399
+ if (firstImported == null) firstImported = { path: rel, content: c };
400
+ if (TAILWIND_IMPORT_RE.test(c)) return { path: rel, content: c }; // anchored sheet wins
401
+ }
402
+ if (firstImported) return firstImported; // the sheet the layout loads, even w/o anchor
403
+ }
404
+ // A conventional stylesheet sitting next to the layout.
405
+ for (const name of ["globals.css", "global.css"]) {
406
+ const rel = path.posix.join(layoutDir, name);
407
+ const c = read(rel);
408
+ if (c != null) return { path: rel, content: c };
409
+ }
410
+ }
411
+
288
412
  // 1. Conventional location that already imports tailwindcss (the anchor).
289
413
  for (const p of CANDIDATE_CSS) {
290
414
  const c = read(p);
@@ -341,7 +465,7 @@ function scanForTailwindCss(cwd, maxDepth = 5) {
341
465
  * @returns {{ok: boolean, path: string|null}}
342
466
  */
343
467
  export function verifyStylesWired(cwd) {
344
- const css = detectGlobalCss(cwd);
468
+ const css = detectGlobalCss(cwd, detectLayoutPath(cwd));
345
469
  return { ok: css.content != null && css.content.includes(STYLE_IMPORT), path: css.path };
346
470
  }
347
471
 
@@ -360,11 +484,24 @@ function readRepoState(cwd) {
360
484
  lockfiles: LOCKFILES.filter((f) => fs.existsSync(path.join(cwd, f))),
361
485
  });
362
486
 
363
- const css = detectGlobalCss(cwd);
364
- const layoutPath = CANDIDATE_LAYOUT.find((p) => fs.existsSync(path.join(cwd, p))) ?? null;
365
-
487
+ // Detect the layout FIRST — both CSS discovery (#8) and language detection (#3)
488
+ // key off it.
489
+ const layoutPath = detectLayoutPath(cwd);
490
+ const language = detectLanguage({
491
+ layoutPath,
492
+ hasTsconfig: fs.existsSync(path.join(cwd, "tsconfig.json")),
493
+ });
494
+ const css = detectGlobalCss(cwd, layoutPath);
495
+
496
+ // Existence set: the CLI-owned providers file lives next to the layout, in the
497
+ // language-matched extension — track both so a re-run is a no-op.
498
+ const providersDir = layoutPath ? path.posix.dirname(toPosix(layoutPath)) : "app";
499
+ const providersCandidates = [
500
+ path.posix.join(providersDir, "ads-providers.tsx"),
501
+ path.posix.join(providersDir, "ads-providers.jsx"),
502
+ ];
366
503
  const _existing = new Set();
367
- for (const p of [...CANDIDATE_CSS, ...CANDIDATE_LAYOUT, "ads-lint.config.mjs", "app/providers.tsx", "src/app/providers.tsx"]) {
504
+ for (const p of [...CANDIDATE_CSS, ...CANDIDATE_LAYOUT, "ads-lint.config.mjs", ...providersCandidates]) {
368
505
  if (fs.existsSync(path.join(cwd, p))) _existing.add(p);
369
506
  }
370
507
 
@@ -376,6 +513,7 @@ function readRepoState(cwd) {
376
513
  layoutContent: layoutPath ? read(layoutPath) : null,
377
514
  hasAdsLintConfig:
378
515
  fs.existsSync(path.join(cwd, "ads-lint.config.mjs")) || fs.existsSync(path.join(cwd, "ads-lint.config.js")),
516
+ language,
379
517
  packageManager,
380
518
  _existing,
381
519
  };
@@ -391,6 +529,13 @@ function applyEdit(cwd, edit) {
391
529
  return;
392
530
  }
393
531
  case "write-file": {
532
+ // NEVER overwrite an existing file (#4): an existing source file — even the
533
+ // CLI-owned providers name — is left untouched and reported, so init can
534
+ // never destroy user content.
535
+ if (fs.existsSync(abs)) {
536
+ console.log(` → skipped ${edit.path} (already exists — left untouched)`);
537
+ return;
538
+ }
394
539
  fs.mkdirSync(path.dirname(abs), { recursive: true });
395
540
  fs.writeFileSync(abs, edit.content);
396
541
  console.log(` → wrote ${edit.path}`);
@@ -408,7 +553,10 @@ function applyEdit(cwd, edit) {
408
553
  } else {
409
554
  content = content.replace(edit.find, edit.replace);
410
555
  }
411
- if (edit.addImport && !content.includes(edit.addImport)) content = `${edit.addImport}\n${content}`;
556
+ // Directive-aware (#5): insert the import AFTER any leading `"use client"`
557
+ // prologue so the directive stays first and `next build` keeps the layout a
558
+ // Client Component.
559
+ if (edit.addImport) content = insertImport(content, edit.addImport);
412
560
  fs.writeFileSync(abs, content);
413
561
  console.log(` → edited ${edit.path}`);
414
562
  return;
@@ -1,29 +1,36 @@
1
1
  import { Badge } from '../badge';
2
- import { CollapsibleContent, CollapsibleTrigger } from '../collapsible';
3
- import { ComponentProps, ComponentType, ReactNode } from 'react';
4
- export type ChainOfThoughtProps = ComponentProps<"div"> & {
5
- open?: boolean;
6
- defaultOpen?: boolean;
7
- onOpenChange?: (open: boolean) => void;
2
+ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../collapsible';
3
+ import { ComponentProps, ReactNode } from 'react';
4
+ /**
5
+ * A step-first reasoning trace. The root is intentionally only a list: each
6
+ * step owns its own disclosure so the trace does not need a redundant global
7
+ * "Chain of Thought" trigger above it.
8
+ */
9
+ export type ChainOfThoughtProps = ComponentProps<"div">;
10
+ export declare const ChainOfThought: import('react').MemoExoticComponent<({ className, role, ...props }: ChainOfThoughtProps) => import("react").JSX.Element>;
11
+ export type ChainOfThoughtStatus = "complete" | "active" | "pending";
12
+ export type ChainOfThoughtStepProps = ComponentProps<typeof Collapsible> & {
13
+ status?: ChainOfThoughtStatus;
8
14
  };
9
- export declare const ChainOfThought: import('react').MemoExoticComponent<({ className, open, defaultOpen, onOpenChange, children, ...props }: ChainOfThoughtProps) => import("react").JSX.Element>;
10
- export type ChainOfThoughtHeaderProps = ComponentProps<typeof CollapsibleTrigger>;
11
- export declare const ChainOfThoughtHeader: import('react').MemoExoticComponent<({ className, children, ...props }: ChainOfThoughtHeaderProps) => import("react").JSX.Element>;
12
- export type ChainOfThoughtStepProps = ComponentProps<"div"> & {
13
- icon?: ComponentType<{
14
- className?: string;
15
- }>;
16
- label: ReactNode;
17
- description?: ReactNode;
18
- status?: "complete" | "active" | "pending";
15
+ export declare const ChainOfThoughtStep: import('react').MemoExoticComponent<({ className, defaultOpen, status, role, ...props }: ChainOfThoughtStepProps) => import("react").JSX.Element>;
16
+ export type ChainOfThoughtTriggerProps = Omit<ComponentProps<typeof CollapsibleTrigger>, "asChild" | "children"> & {
17
+ children: ReactNode;
18
+ /** Semantic icon rendered on the reasoning rail. */
19
+ leftIcon?: ReactNode;
20
+ /** Optional trailing metadata such as elapsed time. */
21
+ endContent?: ReactNode;
22
+ /** Swap the semantic icon for a disclosure affordance on hover. */
23
+ swapIconOnHover?: boolean;
19
24
  };
20
- export declare const ChainOfThoughtStep: import('react').MemoExoticComponent<({ className, icon: Icon, label, description, status, children, ...props }: ChainOfThoughtStepProps) => import("react").JSX.Element>;
25
+ export declare const ChainOfThoughtTrigger: import('react').MemoExoticComponent<({ className, children, leftIcon, endContent, swapIconOnHover, ...props }: ChainOfThoughtTriggerProps) => import("react").JSX.Element>;
26
+ export type ChainOfThoughtContentProps = ComponentProps<typeof CollapsibleContent>;
27
+ export declare const ChainOfThoughtContent: import('react').MemoExoticComponent<({ className, children, ...props }: ChainOfThoughtContentProps) => import("react").JSX.Element>;
28
+ export type ChainOfThoughtItemProps = ComponentProps<"div">;
29
+ export declare const ChainOfThoughtItem: import('react').MemoExoticComponent<({ className, ...props }: ChainOfThoughtItemProps) => import("react").JSX.Element>;
21
30
  export type ChainOfThoughtSearchResultsProps = ComponentProps<"div">;
22
31
  export declare const ChainOfThoughtSearchResults: import('react').MemoExoticComponent<({ className, ...props }: ChainOfThoughtSearchResultsProps) => import("react").JSX.Element>;
23
32
  export type ChainOfThoughtSearchResultProps = ComponentProps<typeof Badge>;
24
33
  export declare const ChainOfThoughtSearchResult: import('react').MemoExoticComponent<({ className, children, ...props }: ChainOfThoughtSearchResultProps) => import("react").JSX.Element>;
25
- export type ChainOfThoughtContentProps = ComponentProps<typeof CollapsibleContent>;
26
- export declare const ChainOfThoughtContent: import('react').MemoExoticComponent<({ className, children, ...props }: ChainOfThoughtContentProps) => import("react").JSX.Element>;
27
34
  export type ChainOfThoughtImageProps = ComponentProps<"div"> & {
28
35
  caption?: string;
29
36
  };