diff --git a/.cursor/rules/README.md b/.cursor/rules/README.md new file mode 100644 index 0000000..b145041 --- /dev/null +++ b/.cursor/rules/README.md @@ -0,0 +1,5 @@ +# Cursor (optional) + +**Cursor** users: start at **[`AGENTS.md`](../../AGENTS.md)**. All conventions live in **`skills/*/SKILL.md`**. + +This folder only points contributors to **`AGENTS.md`** so editor-specific config does not duplicate the canonical docs. diff --git a/.github/workflows/back-merge-pr.yml b/.github/workflows/back-merge-pr.yml new file mode 100644 index 0000000..67cb2ef --- /dev/null +++ b/.github/workflows/back-merge-pr.yml @@ -0,0 +1,60 @@ +# Opens a PR from master → development after changes land on master (back-merge). +# +# Org/repo Settings → Actions → General → Workflow permissions: read and write +# (so GITHUB_TOKEN can create pull requests). Or use a PAT in secret GH_TOKEN. + +name: Back-merge master to development + +on: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + pull-requests: write + +jobs: + open-back-merge-pr: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Open back-merge PR if needed + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + git fetch origin development master + + MASTER_SHA=$(git rev-parse origin/master) + DEV_SHA=$(git rev-parse origin/development) + + if [ "$MASTER_SHA" = "$DEV_SHA" ]; then + echo "master and development are at the same commit; nothing to back-merge." + exit 0 + fi + + EXISTING=$(gh pr list --repo "$REPO" \ + --base development \ + --head master \ + --state open \ + --json number \ + --jq 'length') + + if [ "$EXISTING" -gt 0 ]; then + echo "An open PR from master to development already exists; skipping." + exit 0 + fi + + gh pr create --repo "$REPO" \ + --base development \ + --head master \ + --title "chore: back-merge master into development" \ + --body "Automated back-merge after changes landed on \`master\`. Review and merge to keep \`development\` in sync." + + echo "Created back-merge PR master → development." diff --git a/.github/workflows/check-branch.yml b/.github/workflows/check-branch.yml deleted file mode 100644 index c63e084..0000000 --- a/.github/workflows/check-branch.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: 'Check Branch' - -on: - pull_request: - -jobs: - check_branch: - runs-on: ubuntu-latest - steps: - - name: Comment PR - if: github.base_ref == 'staging' && github.head_ref != 'development' - uses: thollander/actions-comment-pull-request@v2 - with: - message: | - We regret to inform you that you are currently not able to merge your changes into the master branch due to restrictions applied by our SRE team. To proceed with merging your changes, we kindly request that you create a pull request from the development branch. Our team will then review the changes and work with you to ensure a successful merge into the master branch. - - name: Check branch - if: github.base_ref == 'staging' && github.head_ref != 'development' - run: | - echo "ERROR: We regret to inform you that you are currently not able to merge your changes into the master branch due to restrictions applied by our SRE team. To proceed with merging your changes, we kindly request that you create a pull request from the development branch. Our team will then review the changes and work with you to ensure a successful merge into the master branch." - exit 1 \ No newline at end of file diff --git a/.github/workflows/check-version-bump.yml b/.github/workflows/check-version-bump.yml new file mode 100644 index 0000000..5f7d844 --- /dev/null +++ b/.github/workflows/check-version-bump.yml @@ -0,0 +1,77 @@ +# Runs only when production code under src/ changes. Version must be > latest v* tag (not vs base branch). + +name: Check Version Bump + +on: + pull_request: + +jobs: + check-version-bump: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Validate version and changelog updates + shell: bash + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + + VERSION_FILE="package.json" + CHANGELOG_FILE="CHANGELOG.md" + + mapfile -t CHANGED_FILES < <(git diff --name-only "$BASE_SHA" "$HEAD_SHA") + if [ "${#CHANGED_FILES[@]}" -eq 0 ]; then + echo "No changed files detected." + exit 0 + fi + + is_production_source_change() { + local f="$1" + [[ "$f" == src/* ]] + } + + has_source_changes=false + for file in "${CHANGED_FILES[@]}"; do + if is_production_source_change "$file"; then + has_source_changes=true + break + fi + done + + if [ "$has_source_changes" = false ]; then + echo "Skipping: no src/ production code changes." + exit 0 + fi + + changed_file() { + local target="$1" + for file in "${CHANGED_FILES[@]}"; do + if [ "$file" = "$target" ]; then + return 0 + fi + done + return 1 + } + + changed_file "$VERSION_FILE" || { echo "Version bump required in $VERSION_FILE."; exit 1; } + changed_file "$CHANGELOG_FILE" || { echo "Matching changelog update required in $CHANGELOG_FILE."; exit 1; } + + head_version=$(node -e "console.log(require('./package.json').version)") + CHANGELOG_HEAD=$(sed -nE 's/^## v?([^[:space:]]+).*/\1/p' "$CHANGELOG_FILE" | head -1) + + [ -n "$CHANGELOG_HEAD" ] || { echo "::error::Could not find a top changelog heading like '## vX.Y.Z' in $CHANGELOG_FILE."; exit 1; } + [ "$CHANGELOG_HEAD" = "$head_version" ] || { echo "::error::$CHANGELOG_FILE top version ($CHANGELOG_HEAD) does not match project version ($head_version)."; exit 1; } + + latest_tag=$(git tag --list 'v*' --sort=-version:refname | sed -n '1p') + latest_version="${latest_tag#v}" + [ -n "$latest_version" ] || latest_version="0.0.0" + + version_gt() { + python3 -c 'import sys;v=lambda s:[int(x) if x.isdigit() else 0 for x in (s.strip().lstrip("v").split("-",1)[0].split("+",1)[0].split(".")+["0","0","0"])[:3]];print("true" if v(sys.argv[1])>v(sys.argv[2]) else "false")' "$1" "$2" + } + + [ "$(version_gt "$head_version" "$latest_version")" = "true" ] || { echo "Version must be greater than latest tag version ($latest_version). Found $head_version."; exit 1; } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 24e4336..d742ce6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,57 +2,24 @@ name: Unit-Test-CI on: push: - branches: [ master, staging, development ] + branches: [ master, development ] pull_request: - branches: [ master, staging, development ] + branches: [ master, development ] jobs: build-test: runs-on: ubuntu-latest permissions: contents: read - pull-requests: write checks: write + pull-requests: write steps: - uses: actions/checkout@v3 - - name: Check working directory after checkout - run: pwd - - uses: actions/setup-node@v4 - with: - node-version: '22.x' - - name: Check working directory after setup-node - run: pwd - - name: Install dependencies - run: | - pwd - npm ci - - name: Download regions.json - run: | - pwd - ls -la - mkdir -p dist/lib - pwd - npm run download-regions - pwd - ls -la dist/lib/ || echo "dist/lib does not exist" - if [ ! -f dist/lib/regions.json ]; then - echo "Error: regions.json was not downloaded successfully" - exit 1 - fi - - name: Check working directory before tests - run: | - pwd - ls -la - - uses: ArtiomTr/jest-coverage-report-action@v2 + - uses: ArtiomTr/jest-coverage-report-action@7f750dd50f5585533321eb7ebc482b936b49a5d4 # v2 id: coverage-utils-js - continue-on-error: true with: output: comment, report-markdown - test-script: npm test - skip-step: install - uses: marocchino/sticky-pull-request-comment@v2 - continue-on-error: true - if: steps.coverage-utils-js.outputs.report != '' with: header: Contentstack Utils JS Coverage recreate: true @@ -64,4 +31,4 @@ jobs: name: JEST Tests path: reports/junit/jest-*.xml reporter: jest-junit - fail-on-error: true + fail-on-error: true \ No newline at end of file diff --git a/.github/workflows/issues-jira.yml b/.github/workflows/issues-jira.yml deleted file mode 100644 index 7bf0469..0000000 --- a/.github/workflows/issues-jira.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Create Jira Ticket for Github Issue - -on: - issues: - types: [opened] - -jobs: - issue-jira: - runs-on: ubuntu-latest - steps: - - - name: Login to Jira - uses: atlassian/gajira-login@master - env: - JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }} - JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} - JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }} - - - name: Create Jira Issue - id: create_jira - uses: atlassian/gajira-create@master - with: - project: ${{ secrets.JIRA_PROJECT }} - issuetype: ${{ secrets.JIRA_ISSUE_TYPE }} - summary: Github | Issue | ${{ github.event.repository.name }} | ${{ github.event.issue.title }} - description: | - *GitHub Issue:* ${{ github.event.issue.html_url }} - - *Description:* - ${{ github.event.issue.body }} - fields: "${{ secrets.ISSUES_JIRA_FIELDS }}" \ No newline at end of file diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml deleted file mode 100644 index eab0907..0000000 --- a/.github/workflows/npm-publish.yml +++ /dev/null @@ -1,34 +0,0 @@ -# This workflow will publish a package to GitHub Packages when a release is created -# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages - -name: Publish package to NPM repository -on: - release: - types: [created] - -jobs: - publish-npm: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '22.x' - registry-url: 'https://registry.npmjs.org' - - run: npm ci - - run: npm publish - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - publish-git: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '22.x' - registry-url: 'https://npm.pkg.github.com' - scope: '@contentstack' - - run: npm ci - - run: npm publish --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.GIT_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3cbd0e8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,72 @@ +name: Publish package to npmjs registry +on: + release: + types: [published] + +jobs: + publish-npm: + if: ${{ startsWith(github.event.release.tag_name, 'v') && !github.event.release.draft }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.release.tag_name }} + persist-credentials: false + - uses: actions/setup-node@v7 + with: + node-version: 24 + registry-url: https://registry.npmjs.org/ + cache: 'npm' + - name: Check the release tag matches package.json + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + run: | + PKG_VERSION="v$(node -p "require('./package.json').version")" + if [ "$RELEASE_TAG" != "$PKG_VERSION" ]; then + echo "::error::release tag $RELEASE_TAG does not match package.json version $PKG_VERSION" + exit 1 + fi + - run: npm ci + - name: Update npm + run: npm install -g npm@latest + - name: Release + env: + NPM_TAG: ${{ github.event.release.prerelease && 'beta' || 'latest' }} + run: npm publish --access public --tag "$NPM_TAG" + + publish-github: + if: ${{ startsWith(github.event.release.tag_name, 'v') && !github.event.release.draft }} + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.release.tag_name }} + persist-credentials: false + - uses: actions/setup-node@v7 + with: + node-version: 24 + registry-url: https://npm.pkg.github.com/ + cache: 'npm' + - name: Check the release tag matches package.json + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + run: | + PKG_VERSION="v$(node -p "require('./package.json').version")" + if [ "$RELEASE_TAG" != "$PKG_VERSION" ]; then + echo "::error::release tag $RELEASE_TAG does not match package.json version $PKG_VERSION" + exit 1 + fi + - run: npm ci + - name: Update npm + run: npm install -g npm@latest + - name: Release + run: npm publish --access public --tag "$NPM_TAG" + env: + NPM_TAG: ${{ github.event.release.prerelease && 'beta' || 'latest' }} + NODE_AUTH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/sca-scan.yml b/.github/workflows/sca-scan.yml index f09161f..79b6557 100644 --- a/.github/workflows/sca-scan.yml +++ b/.github/workflows/sca-scan.yml @@ -5,6 +5,9 @@ on: jobs: security-sca: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write steps: - uses: actions/checkout@master - name: Run Snyk to check for vulnerabilities @@ -13,3 +16,6 @@ jobs: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} with: args: --all-projects --fail-on=all + json: true + continue-on-error: true + - uses: contentstack/sca-policy@main diff --git a/.github/workflows/secrets-scan.yml b/.github/workflows/secrets-scan.yml deleted file mode 100644 index f9db69f..0000000 --- a/.github/workflows/secrets-scan.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: Secrets Scan -on: - pull_request: - types: [opened, synchronize, reopened] -jobs: - security-secrets: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: '2' - ref: '${{ github.event.pull_request.head.ref }}' - - run: | - git reset --soft HEAD~1 - - name: Install Talisman - run: | - # Download Talisman - wget https://github.com/thoughtworks/talisman/releases/download/v1.37.0/talisman_linux_amd64 -O talisman - - # Checksum verification - checksum=$(sha256sum ./talisman | awk '{print $1}') - if [ "$checksum" != "8e0ae8bb7b160bf10c4fa1448beb04a32a35e63505b3dddff74a092bccaaa7e4" ]; then exit 1; fi - - # Make it executable - chmod +x talisman - - name: Run talisman - run: | - # Run Talisman with the pre-commit hook - ./talisman --githook pre-commit \ No newline at end of file diff --git a/.gitignore b/.gitignore index 582c800..21a9cd3 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,5 @@ coverage/ .dccache snyk_output.log talisman_output.log -regions.json \ No newline at end of file +regions.json +.vscode/settings.json \ No newline at end of file diff --git a/.talismanrc b/.talismanrc index d282969..3d84be8 100644 --- a/.talismanrc +++ b/.talismanrc @@ -1,14 +1,10 @@ fileignoreconfig: -- filename: .github/workflows/secrets-scan.yml - ignore_detectors: - - filecontent -- filename: package-lock.json - checksum: 54777ceb615ca49bc21baf255b1ee9781da7e2868ff3d4292a6715bcbed33196 -- filename: src/entry-editable.ts - checksum: 3ba7af9ed1c1adef2e2bd5610099716562bebb8ba750d4b41ddda99fc9eaf115 -- filename: .husky/pre-commit - checksum: 5baabd7d2c391648163f9371f0e5e9484f8fb90fa2284cfc378732ec3192c193 -- filename: src/endpoints.ts - checksum: 721a1df93b02d04c1c19a76c171fe2748e4abb1fc3e43452e76fecfd8f384751 -- filename: package.json - checksum: 033eb21070795be5b426183f52d784347110fcb724bc9f8d63f94898ac5f0086 \ No newline at end of file + - filename: .github/workflows/secrets-scan.yml + ignore_detectors: + - filecontent + - filename: .github/workflows/ci.yml + checksum: 14991153c5531029f3ac14dbce6fab70aa4b654d445a3514083d446bfadc8813 + - filename: package-lock.json + ignore_detectors: + - filecontent + - base64content diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1afe6f8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,52 @@ +# Contentstack Utils JavaScript – Agent guide + +**Universal entry point** for anyone automating or assisting work in this repo—AI agents (Cursor, Copilot, CLI tools), reviewers, and contributors. Conventions and detailed guidance live in **`skills/*/SKILL.md`**, not in editor-specific config, so the same instructions apply whether or not you use Cursor. + +## What this repo is + +- **Name:** [`@contentstack/utils`](https://www.npmjs.com/package/@contentstack/utils) — [contentstack/contentstack-utils-javascript](https://github.com/contentstack/contentstack-utils-javascript) +- **Purpose:** TypeScript/JavaScript **utilities** for Contentstack: JSON RTE / Supercharged RTE to HTML (`jsonToHTML`), embedded entry and asset rendering (`render`, `renderContent`), GraphQL helpers (`GQL`, `updateAssetURLForGQL`), Live Preview–style editable tags (`addEditableTags`), region endpoint lookup (`getContentstackEndpoint`), and variant-related helpers (`getVariantAliases`, `getVariantMetadataTags`). Used **with** the [Content Delivery API](https://www.contentstack.com/docs/developers/apis/content-delivery-api/) and delivery-shaped JSON (see root `README.md` and [`@contentstack/delivery-sdk`](https://www.npmjs.com/package/@contentstack/delivery-sdk) usage patterns). +- **Out of scope:** This package does **not** ship HTTP clients, stack credentials, or the full CDA/CMA SDK surface. Apps fetch content with the Delivery SDK or other clients, then pass entry JSON into these helpers. Runtime API calls are **not** part of the library; `regions.json` for endpoint lookup is a **build-time** asset. + +## Tech stack (at a glance) + +| Area | Details | +|------|---------| +| Language | TypeScript **4.9** (`tsconfig.json`: `strict: true`, `strictNullChecks: false`) | +| Build | `tsc` → `dist/lib` + declarations in `dist/types/`; **Rollup** → `dist/index.es.js` (`rollup.config.js`). `prebuild` runs `download-regions` for `src/assets/regions.json`. | +| Tests | **Jest 29** + **ts-jest**, **jsdom** (`jest.config.ts`). Tests under **`__test__/**/*.test.ts`**, mocks in **`__test__/mock/`**. | +| Lint / coverage | **ESLint 9** flat config (`eslint.config.js`); **Prettier 3** (`npm run format`). Coverage under `reports/coverage/` when running `npm test`. | +| Runtime | No HTTP client dependency; pure transforms + bundled `regions.json` for endpoints. | + +## Commands (quick reference) + +```bash +npm run build && npm test +npx eslint src __test__ +npm run format +npm run download-regions # regions.json only (also run as part of prebuild) +``` + +`npm test` runs **`pretest` → `npm run build`**, then Jest with coverage; outputs under **`reports/`**. Use **`npm run test:debug`** for Jest watch mode (`--runInBand`). + +**CI:** `.github/workflows/ci.yml` (unit tests / coverage on `development`, `master`). Publish: `.github/workflows/release.yml` (runs when a GitHub **Release** is published for tag `v*`; drafts are skipped) — npm through OIDC trusted publishing, GitHub Packages with the job token. Back-merge automation: `.github/workflows/back-merge-pr.yml`. + +Install: `npm i @contentstack/utils` — see root **`README.md`** and **`package.json`** for the current version. + +## Where the real documentation lives: skills + +Read these **`SKILL.md` files** for full conventions—**this is the source of truth** for implementation and review: + +| Skill | Path | What it covers | +|-------|------|----------------| +| **Development workflow** | [`skills/dev-workflow/SKILL.md`](skills/dev-workflow/SKILL.md) | Branches, CI, build/test/lint, Husky (Snyk/Talisman, commitlint), PR expectations, releases | +| **TypeScript (layout & tooling)** | [`skills/typescript/SKILL.md`](skills/typescript/SKILL.md) | Compiler settings, `src/` layout, ESLint/Prettier, `regions.json` / `.gitignore` | +| **Contentstack Utils (package)** | [`skills/contentstack-utils/SKILL.md`](skills/contentstack-utils/SKILL.md) | Public API and domain: exports from `src/index.ts`, RTE/embed/GQL/endpoints/Live Preview/variants—not the full CDA/CMA SDK; no network layer | +| **Testing** | [`skills/testing/SKILL.md`](skills/testing/SKILL.md) | Jest, mocks, coverage/report paths, `pretest` build, offline unit tests (no stack credentials) | +| **Code review** | [`skills/code-review/SKILL.md`](skills/code-review/SKILL.md) | PR checklist (API docs, compatibility, errors, deps/SCA, tests), Blocker/Major/Minor, terminology | + +There is **no** `skills/framework/` folder: this repo does not ship a shared HTTP client, retry layer, or native build system beyond npm/TypeScript/Rollup. + +## Using Cursor + +If you use **Cursor**, [`.cursor/rules/README.md`](.cursor/rules/README.md) only points to **`AGENTS.md`**—same source of truth as everyone else; no separate `.mdc` rule files. diff --git a/CHANGELOG.md b/CHANGELOG.md index 27e3ac3..da9e0e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,112 +1,186 @@ # Changelog +## [1.9.1](https://github.com/contentstack/contentstack-utils-javascript/tree/v1.9.1) + +- fix: security updates + +## [1.9.0](https://github.com/contentstack/contentstack-utils-javascript/tree/v1.9.0) + +- Feat: Variant utilities `getVariantAliases` and `getVariantMetadataTags` to read variant alias strings from CDA entry `publish_details.variants` (requires fetches with the `x-cs-variant-uid` header set to aliases per [CDA variants](https://www.contentstack.com/docs/developers/apis/content-delivery-api#get-all-entry-variants)). + +## [1.8.0](https://github.com/contentstack/contentstack-utils-javascript/tree/v1.8.0) + +- Fix: JSON-to-HTML now outputs valid HTML for nested lists when JSON RTE exports the nested list as a sibling of the preceding list item (`
  • `). The SDK folds such sibling `
      `/`` + const children = foldNestedListSiblingsIntoPreviousLi(node.children); + return `${sanitizeHTML(next(children))}` }, [NodeType.LIST_ITEM]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, - [NodeType.HR]:(node: Node, next: Next) => { + [NodeType.HR]:() => { return `
      ` }, [NodeType.TABLE]: (node: Node, next: Next) => { // Generate colgroup if colWidths attribute is present let colgroupHTML = ''; - if (node.attrs.colWidths && Array.isArray(node.attrs.colWidths)) { - const totalWidth = node.attrs.colWidths.reduce((sum, width) => sum + width, 0); + const colWidths = getAttr(node, 'colWidths'); + if (colWidths && Array.isArray(colWidths)) { + const totalWidth = colWidths.reduce((sum: number, width: number) => sum + width, 0); colgroupHTML = `<${NodeType.COL_GROUP} data-width="${totalWidth}">`; - node.attrs.colWidths.forEach(colWidth => { + colWidths.forEach((colWidth: number) => { const widthPercentage = (colWidth / totalWidth) * 100; colgroupHTML += `<${NodeType.COL} style="width:${widthPercentage.toFixed(2)}%"/>`; }); @@ -73,78 +136,94 @@ export const defaultNodeOption: RenderOption = { } // Generate table with colgroup and other attributes - return `` + - `${colgroupHTML}` + - `${sanitizeHTML(next(node.children))}` + - ``; + return `${colgroupHTML}${sanitizeHTML(next(node.children))}`; }, [NodeType.TABLE_HEADER]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, [NodeType.TABLE_BODY]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, [NodeType.TABLE_FOOTER]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, [NodeType.TABLE_ROW]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, [NodeType.TABLE_HEAD]:(node: Node, next: Next) => { - if (node.attrs.void) return ''; + if (getAttr(node, 'void')) return ''; - return `${sanitizeHTML(next(node.children))}` + - `` + const rowSpan = getAttr(node, 'rowSpan'); + const colSpan = getAttr(node, 'colSpan'); + const rowSpanAttr = rowSpan ? ` rowspan="${rowSpan}"` : ''; + const colSpanAttr = colSpan ? ` colspan="${colSpan}"` : ''; + + return `${sanitizeHTML(next(node.children))}` }, [NodeType.TABLE_DATA]:(node: Node, next: Next) => { - if (node.attrs.void) return ''; + if (getAttr(node, 'void')) return ''; - return `${sanitizeHTML(next(node.children))}` + - `` + const rowSpan = getAttr(node, 'rowSpan'); + const colSpan = getAttr(node, 'colSpan'); + const rowSpanAttr = rowSpan ? ` rowspan="${rowSpan}"` : ''; + const colSpanAttr = colSpan ? ` colspan="${colSpan}"` : ''; + + return `${sanitizeHTML(next(node.children))}` }, [NodeType.BLOCK_QUOTE]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, [NodeType.CODE]:(node: Node, next: Next) => { - return `${sanitizeHTML(next(node.children))}` + return `${sanitizeHTML(next(node.children))}` }, ['reference']:(node: Node, next: Next) => { - if ((node.attrs.type === 'entry' || node.attrs.type === 'asset') && node.attrs['display-type'] === 'link'){ - let aTagAttrs = `${node.attrs.style ? ` style="${node.attrs.style}"` : ``}${node.attrs['class-name'] ? ` class="${node.attrs['class-name']}"` : ``}${node.attrs.id ? ` id="${node.attrs.id}"` : ``} href="${node.attrs.href || node.attrs.url}"`; - if (node.attrs.target) { - aTagAttrs +=` target="${node.attrs.target}"`; + const type = getAttr(node, 'type'); + const displayType = getAttr(node, 'display-type'); + + if ((type === 'entry' || type === 'asset') && displayType === 'link'){ + const href = getAttrString(node, 'href') || getAttrString(node, 'url') || ''; + const target = getAttrString(node, 'target'); + const assetUid = getAttrString(node, 'asset-uid'); + + let aTagAttrs = buildCommonAttrs(node); + if (href) aTagAttrs += ` href="${href}"`; + if (target) { + aTagAttrs += ` target="${target}"`; } - if(node.attrs.type == 'asset') { - aTagAttrs += ` type="asset" content-type-uid="sys_assets" ${node.attrs['asset-uid'] ? `data-sys-asset-uid="${node.attrs['asset-uid']}"` : ``} sys-style-type="download"` + if (type === 'asset') { + aTagAttrs += ` type="asset" content-type-uid="sys_assets"`; + if (assetUid) { + aTagAttrs += ` data-sys-asset-uid="${assetUid}"`; + } + aTagAttrs += ` sys-style-type="download"`; } - const aTag = `${sanitizeHTML(next(node.children))}`; - return aTag; + return `${sanitizeHTML(next(node.children))}`; } - if (node.attrs.type === 'asset') { - const src = encodeURI(node.attrs['asset-link']); - const alt = node.attrs?.['redactor-attributes']?.['alt']; - const link = node.attrs.link; - const target = node.attrs.target || ""; - const caption = node.attrs?.['redactor-attributes']?.['asset-caption'] || node.attrs?.['asset-caption'] || ""; - const style = node.attrs.style; - const asset_uid= node.attrs['asset-uid']; + + if (type === 'asset') { + const assetLink = getAttrString(node, 'asset-link'); + const src = assetLink ? encodeURI(assetLink) : ''; + const redactorAttrs = getAttr(node, 'redactor-attributes') as Record | undefined; + const alt = redactorAttrs?.['alt'] as string | undefined; + const link = getAttrString(node, 'link'); + const target = getAttrString(node, 'target') || ""; + const caption = (redactorAttrs?.['asset-caption'] as string | undefined) || getAttrString(node, 'asset-caption') || ""; + const style = getAttrString(node, 'style'); + const assetUid = getAttrString(node, 'asset-uid'); + const className = getAttrString(node, 'class-name'); - let imageTag = ``; + const assetUidAttr = assetUid ? ` asset_uid="${assetUid}"` : ''; + const classAttr = className ? ` class="${sanitizeHTML(className)}"` : ''; + const srcAttr = src ? ` src="${sanitizeHTML(src)}"` : ''; + const altAttr = alt ? ` alt="${alt}"` : ''; + const targetAttr = target === "_blank" ? ` target="_blank"` : ''; + const styleAttr = style ? ` style="${style}"` : ''; + + const imageTag = ``; + const styleAttrFig = style ? ` style="${style}"` : ''; - return `` + + return `` + (link ? `` : "") + imageTag + (link ? `` : "") + diff --git a/src/options/default-options.ts b/src/options/default-options.ts index bed35f3..a665d22 100644 --- a/src/options/default-options.ts +++ b/src/options/default-options.ts @@ -16,19 +16,22 @@ export const defaultOptions: RenderOption = { return `${title}`; }, [StyleType.LINK]: (item: EmbeddedItem | EntryNode, metadata: Metadata) => { - const url = encodeURI(sanitizeHTML(item.url || 'undefined')); + const url = item.url ? encodeURI(sanitizeHTML(item.url)) : null; const text = sanitizeHTML(metadata.text || item.title || item.uid || (item.system ? item.system.uid : '')); - return `${text}`; + const hrefAttr = url ? ` href="${url}"` : ''; + return `${text}`; }, [StyleType.DISPLAY]: (item: EmbeddedItem | EntryNode, metadata: Metadata) => { - const url = encodeURI(sanitizeHTML(item.url || 'undefined')); + const url = item.url ? encodeURI(sanitizeHTML(item.url)) : null; const alt = sanitizeHTML(metadata.attributes.alt || item.title || item.filename || item.uid || (item.system ? item.system.uid : '')); - return `${alt}`; + const srcAttr = url ? ` src="${url}"` : ''; + return ``; }, [StyleType.DOWNLOAD]: (item: EmbeddedItem | EntryNode, metadata: Metadata) => { - const href = encodeURI(sanitizeHTML(item.url || 'undefined')); + const href = item.url ? encodeURI(sanitizeHTML(item.url)) : null; const text = sanitizeHTML(metadata.text || item.title || item.uid || (item.system ? item.system.content_type_uid : '')); - return `${text}`; + const hrefAttr = href ? ` href="${href}"` : ''; + return `${text}`; }, }; diff --git a/src/render-embedded-objects.ts b/src/render-embedded-objects.ts index 9aadfed..d091789 100644 --- a/src/render-embedded-objects.ts +++ b/src/render-embedded-objects.ts @@ -5,10 +5,14 @@ import { findEmbeddedItems, findRenderString } from './helper/find-embeded-objec import { EntryEmbedable } from './Models/embedded-object'; import { findRenderContent } from './helper/find-render-content'; /** - * - * @param {EntryEmbedable| EntryEmbedable[]} entry - Objects that contains RTE with embedded objects - * @param {string[]} paths - Key paths for RTE contents in Entry object - * @param {RenderOption?} renderOption - Optional render options to render content + * Renders RTE (Rich Text Editor) content with embedded objects in-place. + * Mutates the entry/entries by replacing embedded item tags with HTML produced + * by the provided render options. Works with a single entry or an array of entries. + * + * @param option - Configuration for rendering. + * @param option.entry - Entry or array of entries containing RTE fields with embedded objects. + * @param option.renderOption - Optional render options (node/item handlers) to produce HTML for embedded content. + * @param option.paths - Optional key paths to specific RTE fields. If omitted, all RTE paths on the entry are rendered. */ export function render(option: { entry: EntryEmbedable| EntryEmbedable[], @@ -46,10 +50,13 @@ export function render(option: { } /** - * - * @param {string | string[]} content - RTE content to render - * @param {EntryEmbedable} options.entry - Entry object containing embedded objects - * @param {RenderOption?} options.renderOption - Optional render options to render content + * Renders a single RTE content string or array of strings by replacing embedded + * item tags with HTML. Uses the entry and renderOption from the given option to + * resolve embedded references and produce output. + * + * @param content - RTE content string or array of strings containing embedded item tags. + * @param option - Must include the entry (for resolving embedded items) and optionally renderOption. + * @returns The same shape as content: a string or array of strings with embedded tags replaced by rendered HTML. */ export function renderContent(content: (string | string[]), option: Option): (string| string[]) { // return blank if content not present diff --git a/src/updateAssetURLForGQL.ts b/src/updateAssetURLForGQL.ts index 29a3e4f..99813ed 100644 --- a/src/updateAssetURLForGQL.ts +++ b/src/updateAssetURLForGQL.ts @@ -1,3 +1,12 @@ +/** + * Updates asset URLs in a GraphQL response in-place. Walks the response data, + * finds RTE fields that have `embedded_itemsConnection`, and sets each + * embedded asset's `asset-link` attribute in the JSON to the asset's `url` + * from the response. Use after fetching content via GraphQL so RTE JSON + * contains correct asset URLs for rendering. + * + * @param gqlResponse - The raw GraphQL response object (e.g. `{ data: { ... } }`). Modified in place. + */ export function updateAssetURLForGQL(gqlResponse:any) { try { const response = gqlResponse?.data; @@ -49,7 +58,7 @@ function findRTEFieldAndUpdateURL(fieldData:any) { } function findRTEField(fieldData: any): any { - if (fieldData && fieldData.embedded_itemsConnection) { + if (fieldData?.embedded_itemsConnection) { return fieldData; } for (const key in fieldData) { diff --git a/src/variant-aliases.ts b/src/variant-aliases.ts new file mode 100644 index 0000000..78e40ac --- /dev/null +++ b/src/variant-aliases.ts @@ -0,0 +1,131 @@ +/** + * Shape returned by {@link getVariantAliases} for interoperability with other Utils SDKs (snake_case JSON keys). + */ +export interface VariantAliasesResult { + entry_uid: string; + contenttype_uid: string; + variants: string[]; +} + +/** CDA entry JSON: at minimum includes `uid`; may include `_content_type_uid` and `publish_details.variants`. */ +export type CDAEntryLike = Record; + +function assertPlainObject(value: unknown, message: string): asserts value is Record { + if (value === null || value === undefined) { + throw new TypeError(message); + } + if (typeof value !== 'object' || Array.isArray(value)) { + throw new TypeError(message); + } +} + +function requireEntryUid(entry: Record): string { + const uid = entry.uid; + if (typeof uid !== 'string' || uid.length === 0) { + throw new Error('Entry uid is required. The entry must include a non-empty uid string.'); + } + return uid; +} + +function resolveContentTypeUid(entry: Record, contentTypeUid?: string): string { + const fromEntry = entry._content_type_uid; + if (typeof fromEntry === 'string' && fromEntry.length > 0) { + return fromEntry; + } + if (typeof contentTypeUid === 'string' && contentTypeUid.length > 0) { + return contentTypeUid; + } + return ''; +} + +function collectVariantAliases(entry: Record): string[] { + const publishDetails = entry.publish_details; + if (!publishDetails || typeof publishDetails !== 'object' || Array.isArray(publishDetails)) { + return []; + } + const variants = (publishDetails as Record).variants; + if (!variants || typeof variants !== 'object' || Array.isArray(variants)) { + return []; + } + const out: string[] = []; + const map = variants as Record; + for (const key of Object.keys(map)) { + const v = map[key]; + if (!v || typeof v !== 'object' || Array.isArray(v)) { + continue; + } + const alias = (v as { alias?: unknown }).alias; + if (typeof alias === 'string' && alias.length > 0) { + out.push(alias); + } + } + return out; +} + +function mapEntryToResult(entry: Record, contentTypeUid?: string): VariantAliasesResult { + return { + entry_uid: requireEntryUid(entry), + contenttype_uid: resolveContentTypeUid(entry, contentTypeUid), + variants: collectVariantAliases(entry), + }; +} + +/** + * Extracts variant **alias** strings from `publish_details.variants` on a CDA entry. + * Only present when the entry was fetched with the `x-cs-variant-uid` header set to variant **aliases** (not UIDs). + * + * @param entry - Single CDA entry object (must include `uid`). + * @param contentTypeUid - Used when `entry._content_type_uid` is missing. Otherwise omitted or empty string yields `contenttype_uid: ""`. + * @returns `{ entry_uid, contenttype_uid, variants }` with snake_case keys for cross-SDK JSON parity. + * @throws TypeError if `entry` is null/undefined or not a plain object. + * @throws Error if `entry` has no non-empty `uid`. + */ +export function getVariantAliases(entry: CDAEntryLike, contentTypeUid?: string): VariantAliasesResult; + +/** + * Extracts variant aliases for each entry in order. + * + * @param entries - Array of CDA entry objects. + * @param contentTypeUid - Applied when an entry lacks `_content_type_uid`. + * @returns One result object per input entry. + * @throws TypeError if `entries` is null/undefined or not an array, or any element is not a plain object. + * @throws Error if any entry has no non-empty `uid`. + */ +export function getVariantAliases(entries: CDAEntryLike[], contentTypeUid?: string): VariantAliasesResult[]; + +export function getVariantAliases( + entryOrEntries: CDAEntryLike | CDAEntryLike[], + contentTypeUid?: string +): VariantAliasesResult | VariantAliasesResult[] { + if (Array.isArray(entryOrEntries)) { + return entryOrEntries.map((e) => { + assertPlainObject(e, 'Each entry must be a plain object with a uid.'); + return mapEntryToResult(e, contentTypeUid); + }); + } + assertPlainObject(entryOrEntries, 'Entry is required. Provide a CDA entry object with a uid.'); + return mapEntryToResult(entryOrEntries, contentTypeUid); +} + +/** + * Serialises variant alias results for use as an HTML `data-csvariants` attribute value. + * + * @param entries - CDA entries to process (same rules as {@link getVariantAliases} for each item). + * @param contentTypeUid - Applied when an entry lacks `_content_type_uid`. + * @returns `{ "data-csvariants": "" }`. + * @throws TypeError if `entries` is null/undefined or not an array, or any element is not a plain object. + * @throws Error if any entry has no non-empty `uid`. + */ +export function getVariantMetadataTags( + entries: CDAEntryLike[], + contentTypeUid?: string +): { 'data-csvariants': string } { + if (entries === null || entries === undefined) { + throw new TypeError('Entries array is required. Provide an array of CDA entry objects.'); + } + if (!Array.isArray(entries)) { + throw new TypeError('Entries must be an array of CDA entry objects.'); + } + const payload = getVariantAliases(entries, contentTypeUid); + return { 'data-csvariants': JSON.stringify(payload) }; +}