Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

7.2 KB
Raw Blame
/**
 * Build the code-mode assets the Rust crates embed: the Deno SDK and Handlebars
 * bundles, the agent documentation catalog, the operation catalog and the SDK
 * declarations routine code is type-checked against.
 *
 * Usage: bun scripts/generate.ts <output-directory>
 */

import { existsSync } from 'node:fs';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { renderSdkDocs } from '@macro-inc/sdk-docs/render';
import ts from 'typescript';
import { entityDirectories } from './catalog';
import { packageEntityDocs, readMarkdownPages } from './typedoc';

const root = fileURLToPath(new URL('../../../', import.meta.url));
const [outputArgument] = Bun.argv.slice(2);
if (!outputArgument)
  throw new Error('usage: bun scripts/generate.ts <output-directory>');
const outputDirectory = resolve(outputArgument);

// Without its own install, the SDK's imports resolve to the root workspace's
// versions of the same packages and the bundle silently differs.
if (!existsSync(join(root, 'packages/sdk/node_modules')))
  throw new Error(
    'packages/sdk/node_modules is missing; run `bun install --frozen-lockfile` in packages/sdk.'
  );

await mkdir(outputDirectory, { recursive: true });

async function artifact(name: string, output: string) {
  await Bun.write(join(outputDirectory, name), output);
}

for (const [entry, name] of [
  ['packages/code-mode-sdk/src/index.ts', 'sdk'],
  ['node_modules/handlebars/dist/handlebars.js', 'handlebars'],
]) {
  const result = await Bun.build({
    entrypoints: [`${root}${entry}`],
    target: 'browser',
    format: 'esm',
    minify: true,
    define: { 'process.env': '{}' },
    plugins: [
      {
        name: 'explicit-service-hosts',
        setup(build) {
          // Runtime hosts are supplied explicitly. Local git/portmap discovery is
          // a CLI convenience and must not pull subprocess/filesystem code into Deno.
          build.onLoad({ filter: /\/sdk\/src\/local-portmap\.ts$/ }, () => ({
            contents:
              'export function resolveLocalPortmap() { return undefined; }',
            loader: 'js',
          }));
        },
      },
    ],
  });
  if (!result.success)
    throw new AggregateError(result.logs, 'SDK build failed');
  const output = result.outputs[0];
  if (!output) throw new Error('No bundle produced');
  await artifact(
    `${name}.mjs`,
    `// Generated by packages/code-mode-sdk/scripts/generate.ts.\n${await output.text()}`
  );
}

const rendered = await mkdtemp(join(outputDirectory, '.docs-'));
try {
  const notes = await renderSdkDocs(root, rendered);
  const pages = await readMarkdownPages(join(rendered, 'markdown'));
  const docs = packageEntityDocs(pages, entityDirectories, notes);
  await artifact('documentation.json', `${JSON.stringify(docs, null, 2)}\n`);
} finally {
  await rm(rendered, { recursive: true, force: true });
}

// The registry comes from generated SDK classes, not hand-maintained endpoint
// paths. `write` decides what a routine's dry run refuses and what its write
// scope covers: every operation that isn't GET or a known read is a write.
type Operation = {
  label: string;
  method: string;
  path: string;
  write: boolean;
};
const operations: Record<string, Operation> = {};
const postReads = new Set([
  'agent-harness.previewAgentSessions',
  'auth.getGithubPullRequestMergeability',
  'auth.getTeamByInviteLink',
  'auth.getUserNames',
  'auth.getUserNamesWithEmail',
  'cognition.decisions',
  'cognition.getBatchPreview',
  'cognition.getChatHistoryBatchMessagesHandler',
  'cognition.getUsageHandler',
  'email.getMessagesBatch',
  'notification.bulkGetTypedNotificationsByEventItemIds',
  'properties.getBulkEntityProperties',
  'search.simpleUnifiedSearch',
  'search.unifiedSearch',
  'storage.getBatchCallRecordPreview',
  'storage.getBatchChannelPreview',
  'storage.getBatchPreviewHandler',
  'storage.getBatchProjectPreview',
  'storage.getGithubPullRequestTasks',
  'storage.mentionPreviews',
  'storage.postItemsSoup',
  'storage.postItemsSoupAst',
  'storage.postItemsSoupAstGrouped',
  'storage.previewSmartTag',
  'storage.queryCrmPipelineRows',
  'storage.taskSimilaritySearchHandler',
  'unfurl.getUnfurlBulk',
]);
const labels: Record<string, string> = {
  'cognition.decisions': 'Classify content',
  'cognition.structuredCompletion': 'Generate structured content',
  'storage.postItemsSoupAst': 'Browse workspace',
  'search.unifiedSearch': 'Search workspace',
  'search.simpleUnifiedSearch': 'Search workspace',
  'storage.getDocument': 'Read document',
  'storage.getUserDocumentsHandler': 'List documents',
  'storage.postItemsSoupAstGrouped': 'Browse workspace',
};
for (const [service, directory] of Object.entries({
  'agent-harness': 'agent-harness',
  auth: 'auth',
  calendar: 'calendar',
  cognition: 'cognition',
  contacts: 'contacts',
  email: 'email',
  notification: 'notification',
  properties: 'properties',
  search: 'search',
  'scheduled-action': 'scheduled-action',
  unfurl: 'unfurl',
  storage: 'storage',
})) {
  const { Sdk } = await import(
    `${root}packages/sdk/generated/${directory}/sdk.gen.ts`
  );
  for (const name of Object.getOwnPropertyNames(Sdk.prototype)) {
    if (name === 'constructor') continue;
    const key = `${service}.${name}`;
    const body = String(Sdk.prototype[name]);
    const method = body.match(/\.(get|post|put|patch|delete|head)\s*\(/)?.[1];
    const path = body.match(/url:\s*["'`]([^"'`]+)["'`]/)?.[1];
    if (!method || !path) throw new Error(`${key} has no method or url`);
    operations[key] = {
      label:
        labels[key] ??
        name
          .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
          .replace(/Handler$/, '')
          .replace(/^./, (letter: string) => letter.toUpperCase())
          .trim(),
      method: method.toUpperCase(),
      path,
      write: !(method === 'get' || method === 'head' || postReads.has(key)),
    };
  }
}
for (const key of postReads)
  if (!operations[key]) throw new Error(`unknown read operation ${key}`);
await artifact('operations.json', `${JSON.stringify(operations, null, 2)}\n`);

// Declarations that stored routine code is type-checked against, and the
// fingerprint a routine records: the SDK version plus a hash of these types,
// so any change to the API's shape is a new fingerprint.
const sdkRoot = join(root, 'packages/sdk');
const config = ts.getParsedCommandLineOfConfigFile(
  join(sdkRoot, 'tsconfig.build.json'),
  { removeComments: true },
  { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }
);
if (!config) throw new Error('SDK tsconfig.build.json is unreadable');
const declarations: Record<string, string> = {};
const emitted = ts
  .createProgram(config.fileNames, config.options)
  .emit(undefined, (file, text) => {
    declarations[relative(config.options.outDir ?? '', file)] = text;
  });
if (emitted.emitSkipped) throw new Error('SDK declarations failed to emit');
const files = Object.fromEntries(
  Object.entries(declarations).sort(([a], [b]) => a.localeCompare(b))
);
const { version } = await Bun.file(join(sdkRoot, 'package.json')).json();
const hash = new Bun.CryptoHasher('sha256')
  .update(JSON.stringify(files))
  .digest('hex')
  .slice(0, 12);
await artifact(
  'sdk-types.json',
  `${JSON.stringify({ fingerprint: `${version}+${hash}`, files })}\n`
);