# AGENTS.md

This file provides guidance to AI coding assistants (Claude Code, GitHub Copilot, Codex, etc.) when working with code in
this repository.

## Before Starting Any Task

Read `README.md` Table of Contents first — it contains sections on template development, helper functions, mapping logic,
and examples not repeated in this file. Check which sections are relevant before writing any code.

## After Changing Any Template

Run the tests after every template change:

```bash
npm test
```

If snapshots need updating (expected output changed intentionally):

```bash
npm test -- --updateSnapshot
```

## Overview

This is a template repository for the
[Constructor.io Connect CLI](https://www.npmjs.com/package/@constructor-io/constructorio-connect-cli). It contains
JSONata templates that transform catalog data (items, variations, item groups, mappings) for the Constructor Connect
platform.

## Repository Structure

- `connectrc.js` — Configuration mapping connections (by ID) to template files, per environment (development/qa/production)
- `src/templates/` — JSONata templates (item, variation, item_group, mapping)
- `src/templates/helpers.jsonata` — Shared helper functions importable in other templates
- `src/fixtures/` — JSON fixture files for testing template execution
- `test/templates/` — Jest snapshot tests (`.spec.mjs` files)
- `.env` — Auth token (not committed); copy `.env.example` and set `CONNECT_AUTH_TOKEN=<your token>`

## Commands

```bash
# Install dependencies
npm install

# Run all tests
npm test

# Run a single test file
npm test -- --testPathPattern=item

# Update snapshots
npm test -- --updateSnapshot

# Run tests with console output visible
npm test -- --verbose

# Lint
npm run lint
npm run lint:fix

# Execute a template interactively (prompts for connection/fixture)
npm run execute

# Execute a specific template with flags
npm run execute -- --template-path=item/item.jsonata --fixture-path=item/item.json

# Deploy templates to an environment
npm run deploy development
npm run deploy production

# Generate a fixture from server data (interactive)
npm run generate-fixture

# Generate a fixture non-interactively (read connection ID from connectrc.js)
npm run generate-fixture -- --connection=<connection-id> --type=item --item-id=<id> --filename=item.json --replace-file

# Trigger a catalog sync
npm run trigger-catalog-sync
```

There is also a root-level `execute-template.js` that VSCode uses (via F5 / launch.json) to execute the currently open
template file.

## Architecture

### Template Language

Templates use JSONata, a query and transformation language for JSON. Templates receive:

- `data` — The incoming data to be transformed
- `external` — External data available from the connector (e.g. connection settings like locale)
- `targetData` — Alias for `data` (deprecated, prefer `data`)
- `externalData` — Alias for `external` (deprecated, prefer `external`)

### Template Types

- **item.jsonata** — Transforms source data into Constructor item format. Returns
  `{ id, active, keywords, group_ids, metadata, facets }`. Return `{ "remove": true }` to exclude an item.
- **variation.jsonata** — Transforms variation data. Must include `variation_id` and `item_id`. Return
  `{ "remove": true }` to exclude a variation.
- **item_group.jsonata** — Transforms item group/category data.
- **mapping.jsonata** — Pre-processes data before transformation. Can return `{ items, variations, item_groups }` arrays.
  Used for reshaping, filtering, or creating lookup maps.
- **helpers.jsonata** — Shared functions imported in other templates via `/*{{helpers}}*/`. Define functions with the
  `$fn := function($arg) { ... }` pattern:

  ```jsonata
  /* Helpers will be available in every template that imports them with {{helpers}} */

  $getAttributeValue := function($name) {
    data.attributes[name = $name].value
  };
  ```

  Import in a template by placing `/*{{helpers}}*/` at the top:

  ```jsonata
  /*{{helpers}}*/

  {
    "id": data.id,
    "name": $getAttributeValue("name")
  }
  ```

### Test Structure

- Tests use Jest with `.spec.mjs` extension and babel-jest transform
- Tests rely on `executeTemplate` and `buildFixture` from `@constructor-io/constructorio-connect-cli`
- Snapshot-based testing is the primary pattern
- `test/global-setup.js` loads connections via API (requires `CONNECT_AUTH_TOKEN` in `.env`)
- Console logs are suppressed during tests unless `--verbose` is passed
- `buildFixture` accepts an optional third argument (object) that deep merges into the fixture — use it to override
  fields instead of mutating the fixture directly: `buildFixture("item", "item.json", { Published: "False" })`
- Test timeout is 30s (templates execute via HTTP)

### executeTemplate Options

`executeTemplate` accepts these options:

| Option         | Type     | Description                                                                                       |
| -------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `type`         | `string` | Template type: `"item"`, `"variation"`, `"item_group"`, `"mapping"`                               |
| `name`         | `string` | Template filename (e.g. `"item.jsonata"`)                                                         |
| `fixture`      | `object` | Input data — use `buildFixture(type, file, overrides?)`                                           |
| `external`     | `object` | External/connection data. Can be `buildFixture("external_data", "file.json")` or an inline object |
| `connectionId` | `string` | Explicit connection ID, e.g. `process.env.LOCAL_CONNECTION_ID`                                    |

### Testing Patterns

**Basic snapshot** — covers the full output in one assertion:

```js
it("should match snapshot", async () => {
  const result = await executeTemplate({
    type: "item",
    name: "item.jsonata",
    fixture: buildFixture("item", "item.json"),
  });
  expect(result).toMatchSnapshot();
});
```

**Field-level assertions** — preferred when testing a specific behavior or edge case:

```js
it("should return undefined hover_image_url when only one image exists", async () => {
  const result = await executeTemplate({
    type: "item",
    name: "item.jsonata",
    fixture: buildFixture("item", "item.json", {
      __media: [{ src: "img.jpg" }],
    }),
  });
  expect(result.metadata.hover_image_url).toBeUndefined();
});
```

**External data** — pass a fixture file or an inline object as `external`:

```js
// From fixture file:
const result = await executeTemplate({
  type: "variation",
  name: "variation.jsonata",
  fixture: buildFixture("variation", "variation.json"),
  external: buildFixture("external_data", "external_data_qa.json"),
});

// Inline object (useful for connection settings or lookup maps):
const result = await executeTemplate({
  type: "item",
  name: "item.jsonata",
  fixture: buildFixture("item", "item.json"),
  external: {
    __connection: { ingestionType: "FULL" },
    productById: { "id-1": { name: "Example" } },
  },
});
```

**Multiple fixture files** — create separate fixture files for distinct scenarios instead of complex overrides:

```js
// src/fixtures/variation/variation.json — default case
// src/fixtures/variation/variation_with_discount.json — discount case
describe("variation with discount", () => {
  it("should match snapshot", async () => {
    const result = await executeTemplate({
      type: "variation",
      name: "variation.jsonata",
      fixture: buildFixture("variation", "variation_with_discount.json"),
    });
    expect(result).toMatchSnapshot();
  });
});
```

**Shared execution with `beforeEach`** — execute once, assert multiple fields separately:

```js
describe("variation for MX market", () => {
  let result;

  beforeEach(async () => {
    result = await executeTemplate({
      type: "variation",
      name: "variation.jsonata",
      fixture: buildFixture("variation", "variation_mx.json"),
      external: buildFixture("external_data", "external_data_mx.json"),
    });
  });

  it("should set stock", () => {
    expect(result.metadata.find((m) => m.key === "stock").value).toBe(30);
  });

  it("should set availableRegions", () => {
    expect(
      result.metadata.find((m) => m.key === "availableRegions").value,
    ).toStrictEqual(["MX"]);
  });
});
```

**Nested `describe` blocks** — group related edge cases:

```js
describe("item", () => {
  it("should match snapshot", async () => {
    /* ... */
  });

  describe("hover image", () => {
    it("should pick the 2nd image as hover_image_url", async () => {
      /* ... */
    });
    it("should return undefined when only one image exists", async () => {
      /* ... */
    });
  });
});
```

**Skip unused template types** — when a customer does not use a template type, skip its suite rather than deleting the file:

```js
// This customer does not have variations
describe.skip("variation", () => {
  it("should match snapshot", async () => {
    /* ... */
  });
});
```

### Global Helper Functions

**Before writing any template code**, fetch and read the current global helper function reference — do not assume what
helpers exist or reimplement them in `helpers.jsonata`.

Reference: <https://docs.constructor.com/docs/integrating-with-constructor-connect-cli-helper-functions-global-helper-functions>

### connectrc.js

Each project's `connectrc.js` defines a `connections` map and a `config` export:

```js
// @ts-check

const connections = {
  "My Store: Dev": {
    id: "uuid-here",
    slug: "con_xxx",
    environment: "development",
  },
  "My Store: QA": {
    id: "uuid-here",
    slug: "con_yyy",
    environment: "qa",
  },
  "My Store: Prod": {
    id: "uuid-here",
    slug: "con_zzz",
    environment: "production",
  },
};

/** @type {import("@constructor-io/constructorio-connect-cli/dist/types").Config} */
const config = {
  helpers: "src/templates/helpers.jsonata",
  environments: [
    {
      environment: "development",
      templates: [
        {
          connection_ids: [connections["My Store: Dev"].id],
          paths: {
            item: "src/templates/item/item.jsonata",
            variation: "src/templates/variation/variation.jsonata",
            item_group: "src/templates/item_group/item_group.jsonata",
            mapping: "src/templates/mapping/mapping.jsonata",
          },
        },
      ],
    },
    {
      environment: "qa",
      templates: [
        {
          connection_ids: [connections["My Store: QA"].id],
          paths: {
            item: "src/templates/item/item.jsonata",
            variation: "src/templates/variation/variation.jsonata",
            item_group: "src/templates/item_group/item_group.jsonata",
            mapping: "src/templates/mapping/mapping.jsonata",
          },
        },
      ],
    },
    {
      environment: "production",
      templates: [
        {
          connection_ids: [connections["My Store: Prod"].id],
          paths: {
            item: "src/templates/item/item.jsonata",
            variation: "src/templates/variation/variation.jsonata",
            item_group: "src/templates/item_group/item_group.jsonata",
            mapping: "src/templates/mapping/mapping.jsonata",
          },
        },
      ],
    },
  ],
};

module.exports = config;
```

Key points:

- `helpers` — path to the shared helpers file; makes helper functions available via `/*{{helpers}}*/` in templates
- `paths` — maps each template type to its file path; omit types not in use
- Multiple `templates` objects per environment are allowed — useful when different connections use different template sets
