Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

6.3 KB
Raw Blame
const fs = require("node:fs");
const path = require("node:path");
const { withXcodeProject } = require("@expo/config-plugins");
const { patchIncomingShareFormats } = require("./with-incoming-share-formats");
const { patchShareFeedback } = require("./with-incoming-share-feedback");

// expo-sharing 57 copies files to AppGroup/<basename>, overwriting same-name
// files even within one share. Keep each input in its own directory, retaining
// the basename for display. Do not modify the installed dependency/template.
function patchShareExtension(source) {
  const replace = (from, to, count) => {
    if (source.split(from).length - 1 !== count) {
      throw new Error(
        "expo-sharing template changed; review incoming-file ownership patch",
      );
    }
    source = source.split(from).join(to);
  };
  replace(
    "  private func handleShare() {",
    "  private var shareStarted = false\n\n  private func handleShare() {\n    guard !shareStarted else { return }\n    shareStarted = true",
    1,
  );
  replace(
    "    let destinationURL = containerURL.appendingPathComponent(fileName)",
    '    let directory = containerURL.appendingPathComponent("cindy-share-" + UUID().uuidString, isDirectory: true)\n    let destinationURL = directory.appendingPathComponent(fileName)',
    2,
  );
  replace(
    "      if FileManager.default.fileExists(atPath: destinationURL.path) {\n        try FileManager.default.removeItem(at: destinationURL)\n      }",
    "      try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)",
    1,
  );
  replace(
    "      try data.write(to: destinationURL)",
    "      try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n      try data.write(to: destinationURL)",
    1,
  );
  replace(
    "      userDefaults.set(encoded, forKey: SHARE_INTO_DEFAULTS_KEY)\n      userDefaults.synchronize()",
    '      do {\n        try IncomingShareSlot.write(encoded, group: appGroupId)\n        return true\n      } catch {\n        print("Error: incoming share could not be saved")\n        return false\n      }',
    1,
  );
  replace(
    "        saveToUserDefaults(payload)",
    "        guard saveToUserDefaults(payload) else {\n          self.close()\n          return\n        }",
    1,
  );
  replace(
    "  private func saveToUserDefaults(_ payload: [SharePayload]) {",
    "  private func saveToUserDefaults(_ payload: [SharePayload]) -> Bool {",
    1,
  );
  replace(
    '    guard let userDefaults = UserDefaults(suiteName: appGroupId) else {\n      print("Error: Expo-sharing could not initialize UserDefaults with group: \\(appGroupId)")\n      return\n    }',
    "",
    1,
  );
  replace(
    '      print("Error: Expo-sharing has failed to serialize shared data to JSON")',
    '      print("Error: Expo-sharing has failed to serialize shared data to JSON")\n      return false',
    1,
  );
  source = patchIncomingShareFormats(source);
  return (
    patchShareFeedback(source) +
    "\n" +
    fs.readFileSync(
      path.join(
        __dirname,
        "../modules/cindy-incoming-share/ios/IncomingShareSlot.swift",
      ),
      "utf8",
    )
  );
}

module.exports = (config) =>
  withXcodeProject(config, (mod) => {
    // Xcode mods run after expo-sharing's dangerous mod writes the fresh template.
    const file = path.join(
      mod.modRequest.platformProjectRoot,
      "expo-sharing-extension",
      "ShareIntoViewController.swift",
    );
    fs.writeFileSync(file, patchShareExtension(fs.readFileSync(file, "utf8")));
    const plist = require('@expo/plist').default;
    const folder = path.dirname(file);
    const infoPath = path.join(folder, 'Info.plist');
    const info = plist.parse(fs.readFileSync(infoPath, 'utf8'));
    const attributes = info.NSExtension.NSExtensionAttributes;
    // Match exportable representations, including mixed shares and custom data.
    // No TRUEPREDICATE: unsupported provider-only objects do not advertise Cindy.
    attributes.NSExtensionActivationRule = 'SUBQUERY(extensionItems, $item, SUBQUERY($item.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.data" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.url" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.text" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.directory" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "com.apple.property-list").@count == $item.attachments.@count).@count == extensionItems.@count';
    attributes.NSExtensionJavaScriptPreprocessingFile = 'incoming-share-webpage';
    fs.writeFileSync(infoPath, plist.build(info));
    const jsName = 'incoming-share-webpage.js';
    fs.copyFileSync(path.join(__dirname, jsName), path.join(folder, jsName));
    const project = mod.modResults;
    const targets = project.pbxNativeTargetSection();
    const target = Object.keys(targets).find(key => !key.endsWith('_comment') && String(targets[key].name).replaceAll('"', '') === 'expo-sharing-extension');
    if (!target) throw new Error('expo-sharing extension target missing');
    const resourcePath = 'expo-sharing-extension/' + jsName;
    const added = project.addResourceFile(resourcePath, { target });
    // Expo-created phases can lack the comments xcode's target lookup needs.
    // Resolve by ISA instead, including an existing reference on repeated prebuilds.
    const references = project.pbxFileReferenceSection();
    const reference = added?.fileRef ?? Object.keys(references).find(key =>
      !key.endsWith('_comment') && String(references[key].path).replaceAll('"', '') === resourcePath);
    const builds = project.pbxBuildFileSection();
    const build = added?.uuid ?? Object.keys(builds).find(key =>
      !key.endsWith('_comment') && builds[key].fileRef === reference);
    const phases = project.hash.project.objects.PBXResourcesBuildPhase;
    const phase = targets[target].buildPhases.map(item => phases[item.value]).find(Boolean);
    if (!build || !phase) throw new Error('expo-sharing resource phase missing');
    for (const [key, value] of Object.entries(phases)) {
      if (!key.endsWith('_comment')) value.files = value.files.filter(item => item.value !== build);
    }
    phase.files.push({ value: build, comment: jsName + ' in Resources' });
    return mod;
  });
module.exports.patchShareExtension = patchShareExtension;